Home >Backend Development >Golang >How to create golang method?
Steps to create a Go method: 1. Define the method syntax: func (receiver_type) method_name (parameters) return_type; 2. Call the method: instance_of_struct_type.method_name (arguments).
In Go, a method is a function bound to a struct type. To create a method in a struct type, use the following syntax:
func (receiver_type) method_name(parameters) return_type
where
receiver_type
is the struct type to which the method belongs. method_name
is the name of the method. parameters
is the list of parameters accepted by the method. return_type
is the type returned by the method. Create a Person
structure with a getName
method:
type Person struct { name string } func (p Person) getName() string { return p.name }
To call a method, use the following syntax:
instance_of_struct_type.method_name(arguments)
where
instance_of_struct_type
is the instance of the structure on which the method is to be called. method_name
is the name of the method to be called. arguments
are the parameters to be passed to the method. Consider a web application that manages a list of users. We can create a User
structure to represent the user, which contains the getName
and setName
methods:
type User struct { name string } func (u *User) getName() string { return u.name } func (u *User) setName(name string) { u.name = name }
We can use these methods to retrieve And modify the user's name:
user := &User{name: "John Doe"} fmt.Println(user.getName()) // 输出:"John Doe" user.setName("Jane Doe") fmt.Println(user.getName()) // 输出:"Jane Doe"
The above is the detailed content of How to create golang method?. For more information, please follow other related articles on the PHP Chinese website!