In Go, a function can be assigned to a struct, giving it the ability to perform actions related to its data. This concept is known as a method.

Let’s take a look at an example:

type Person struct {
    Name string
    Age  int
}

func (p Person) Speak() {
    fmt.Println("Hello from " + p.Name)
}

func main() {
    flavio := Person{Age: 39, Name: "Flavio"}
    flavio.Speak()
}

In this example, we define a Person struct with two fields, Name and Age. The Speak() method is associated with the Person struct and can be called on an instance of that struct. When flavio.Speak() is called, it prints “Hello from Flavio” to the console.

Methods can be declared with either a pointer receiver or a value receiver.

In the above example, the method Speak() is a value receiver. It receives a copy of the struct instance when called.

Alternatively, we can use a pointer receiver, which receives the pointer to the struct instance. Here’s an example:

func (p *Person) Speak() {
    fmt.Println("Hello from " + p.Name)
}

Using a pointer receiver enables us to modify the original struct instance. This can be useful when working with larger structs or when we want changes made within the method to reflect on the original instance.

By leveraging methods in Go, we can enhance our structs with custom functionality, making our code more organized and maintainable.