Go Struct Methods: A Complete Guide

In Go language, there is no concept of classes, but similar object-oriented programming functionality can be achieved through structs and methods. Methods can be defined for structs in Go language, with methods being a type of attribute for the struct allowing for operations on the struct to be implemented.

Declare a structure:

type Person struct {
    Name string
    Age  int
}

Define methods for a struct:

func (p *Person) SayHello() {
    fmt.Printf("Hello, my name is %s and I am %d years old\n", p.Name, p.Age)
}

When defining a method, it is necessary to add a receiver in front of the function name, and the receiver is a struct type. In this example, the SayHello method defines a method for the Person struct, allowing access to the fields within the struct and outputting the corresponding information.

Usage instructions:

func main() {
    p := Person{Name: "Alice", Age: 30}
    p.SayHello()
}

Create an instance of the Person struct in the main function and call the SayHello method to output information. By defining and using methods, we can achieve similar functionality to object-oriented programming.

bannerAds