Home > Article > Backend Development > What is a receiver in Go language?
In the Go language, a receiver refers to a parameter that exists as a parameter of a method. Every method will have a receiver. The combination of receivers and methods is actually how object-oriented programming is implemented in the Go language.
The receiver is usually used as the first parameter of the method. It has its own type, which can be a pointer type or a non-pointer type. Pointer type receivers are mainly used to modify the variable pointed to by the receiver, while non-pointer type receivers are mainly used to transfer value types.
It should be noted that during the method call, the receiver must be of the same type as the value passed into the method. If it is a pointer type receiver, the corresponding value also needs to be of pointer type; and if it is a non-pointer type receiver, the corresponding value also needs to be of non-pointer type.
For example, suppose we define a structure as follows:
type User struct{ name string age int }
Now we want to define a method for this structure to print user information. We can define the following method:
func (u User) PrintInfo(){ fmt.Printf("name: %s, age: %d", u.name, u.age) }
At this point, we can print the user's information by calling the PrintInfo method:
user := User{"Jack", 18} user.PrintInfo() // 输出:name: Jack, age: 18
The type of receiver u is User, which represents this method It belongs to the User structure. In the definition of the method, we access the member variables in the structure through u.name and u.age. Finally, when we call the method, we can call the method directly through user.PrintInfo().
In addition to value type receivers, the Go language also supports pointer type receivers. Through the pointer type receiver, we can modify the member variables in the structure instance.
For example, we now want to define a method for increasing the age of the User structure. We can define the following method:
func (u *User) AddAge(i int){ u.age += i }
At this point, we can increase the user's age by calling the AddAge method:
user := &User{"Tom", 20} user.AddAge(1) user.PrintInfo() // 输出:name: Tom, age: 21
It should be noted that what is passed in here is the user's pointer, not the value of the structure. This is because the receiver is of pointer type, so the corresponding pointer needs to be passed in.
In addition, it is important to note that if the receiver of a method is of non-pointer type, then any modification operation on it will generate a new value. Therefore, special attention is required when designing methods.
In general, the receiver is a very important concept in the Go language. By using receivers properly and rationally, we can easily implement the functions of object-oriented programming.
The above is the detailed content of What is a receiver in Go language?. For more information, please follow other related articles on the PHP Chinese website!