Home >Backend Development >Golang >How to define and use class methods in Golang
With the development of Golang in recent years, its application scenarios and scope of use have continued to expand. The class method is a commonly used method in Golang, which can easily use and call methods in the class. This article will introduce how to define and use class methods in Golang.
1. Define class methods
In Golang, class methods are methods defined in the structure. Structure is a keyword used to define objects in Golang, similar to classes in other programming languages. Defining methods in a structure makes it easier for us to use and operate the properties in the structure.
The following is an example to illustrate how to define class methods in Golang:
type Person struct { Name string Age int } func (p Person) SayHello() { fmt.Printf("Hello, my name is %s, I am %d years old", p.Name, p.Age) }
In the above code, we define a Person structure and a SayHello method. This method can output a person's name and age.
Among them, we use the difference between function (func) and method (method). The difference between method and function is that the method has a receiver (receiver), that is, the calling method can be accessed in the method. Structure or object.
2. Use class methods
Once the structure and methods are defined, we can call the methods by creating objects of the structure. The following is an example:
func main() { person := Person{ Name: "Tom", Age: 18, } person.SayHello() }
In the above code, we create a Person object, and then output the name and age of the Person by calling the SayHello method.
In addition, we can also use structures as function parameters or return values, or define class methods through pointers. Here is an example:
func (p *Person) AddAge() { p.Age += 1 } func NewPerson(name string, age int) *Person { return &Person{ Name: name, Age: age, } } func main() { person := NewPerson("Tom", 18) person.AddAge() person.SayHello() }
In the above code, we define the AddAge method through a pointer, and then define a NewPerson method that returns a pointer to the Person object. In the main function, we create a Person object through NewPerson, then call the AddAge method to increase the Person's age and output the Person's information.
Summary:
In Golang, class methods can conveniently use and operate the attributes in the structure. By defining a receiver, we can access the structure or object that calls the method in the method. At the same time, we can also use structures as function parameters or return values, and we can also define class methods through pointers. I hope this article can help everyone better understand class methods in Golang.
The above is the detailed content of How to define and use class methods in Golang. For more information, please follow other related articles on the PHP Chinese website!