go go/book/learninggo

A Method is a function that is associated with a specific type.
Methods are used to add behavior to types, especially custom types like Struct, making them essential for object-oriented programming in Go.
They allow you to define functions that operate on the data contained within a specific instance of a type.

Methods - Practical Go Lessons

Remember

A method is just a function with a receiver argument.

Go - Visibility

Method vs Function

AspectMethodFunction
Type associationAssociated with a specific type via a receiverNot associated with any specific type
ReceiverHas a receiver parameterNo receiver
PurposeAdds behavior to a type, supports encapsulationGeneral-purpose
InterfacesCan be part of an interface method setCannot be part of an interface
InvocationCalled on a specific instance of the typeCalled directly by function name
// Method with a receiver of type `Person`
func (p *Person) UpdateName(newName string) {
    p.Name = newName
}
 
// Function without a receiver
func updateName(p *Person, newName string) {
    p.Name = newName
}

Method Receivers: Value vs. Pointer

1. Value Receiver (func (p Person) Greet() {...})

  • A copy of the value is made when the method is called.
  • The original value remains unchanged if modified within the method.
  • Value receivers are typically used when you don’t need to modify the receiver’s data or for small types where copying is inexpensive.

2. Pointer Receiver (func (p *Person) Greet() {...})

  • A pointer to the receiver value is passed to the method.
  • Modifications made within the method affect the original value.
  • Pointer receivers are used when you want the method to modify the receiver’s data or for large types to avoid copying overhead.