What's Inside the Parentheses in Go Function Declarations?
In Go, you might encounter function declarations with syntax like this:
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ... }
func (s *GracefulServer) BlockingClose() bool { ... }
What's inside the parentheses, such as (h handler) and (s *GracefulServer), is known as the "receiver". The way it works in Go differs from other languages.
The Receiver as a Class
The receiver type, like a class in object-oriented programming, represents the entity on which methods are invoked. For instance, if A is a method within class Person, an instance of Person is required to call A.
Receiver as Value or Pointer
In the examples above, h is a value type while s is a pointer. This distinction affects how the method operates:
When to Use Pointers
Use pointers as receivers when you want to modify the state of the receiver. For example, if you need BlockingClose to alter the state of GracefulServer, s *GracefulServer is necessary.
Spec Reference:
For more details, refer to the official Go specification: https://golang.org/ref/spec#Method_sets
The above is the detailed content of What Does the Receiver in Go Function Declarations Do?. For more information, please follow other related articles on the PHP Chinese website!