Sobes.tech
Junior — Middle

What methods belong to data structures or classes?

sobes.tech AI

Answer from AI

In Go, methods are functions that are associated with a specific data type (a struct or a class, although Go does not have classes in the traditional sense). A method is declared with a receiver, which indicates the type it belongs to.

Example of a method for a struct:

package main
import "fmt"

type Person struct {
    Name string
    Age  int
}

// Method with receiver of type Person
func (p Person) Greet() {
    fmt.Printf("Hello, my name is %s and I am %d years old\n", p.Name, p.Age)
}

func main() {
    person := Person{Name: "Ivan", Age: 30}
    person.Greet() // calling the method
}

Thus, methods are functions declared with a receiver that links them to a specific struct or type. They allow working with the data of the struct and implementing behavior associated with this type.

What methods belong to data structures or classes… - sobes.tech