In Go, a method is a function with a special receiver argument that is associated with a specific type. It allows you to define behavior that operates on instances of that type.
Methods can only be defined on named types. They cannot be defined on unnamed types such as []int or
map[string]int.
A named type is any type that is declared using the type keyword and given its own name.
receiver: The variable that represents the instance the method is called on.
receiverType: The type the method is attached to.
methodName: The name of the method being defined.
parameters: The input arguments the method accepts (optional).
returnType: The value type the method returns (optional).
Declare:
type person struct { name string age int}func (p person) sayHello() { fmt.Println("Hello, my name is " + p.name)}
You can only declare a method on a receiver type defined in the same package.
Call:
user := person{name: "John", age: 35}user.sayHello() // Hello, my name is John
To allow a method to modify the original data in types that use pass-by-value (Pure Value Types) semantics, the method must use a pointer receiver.
func (p *person) changeName(name string) { p.name = name // `(*p).name = name` is also valid, but unnecessary in Go.}func main() { user := person{name: "John", age: 35} user.sayHello() // Hello, my name is John user.changeName("Jane") user.sayHello() // Hello, my name is Jane}
Go automatically dereferences struct pointers when accessing fields. That is why we write p.name = name instead of (*p).name = name.