Home > Backend Development > Golang > What Does the Receiver in Go Function Declarations Do?

What Does the Receiver in Go Function Declarations Do?

DDD
Release: 2024-12-20 10:55:21
Original
198 people have browsed it

What Does the Receiver in Go Function Declarations Do?

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) {
    ...
}
Copy after login
func (s *GracefulServer) BlockingClose() bool {
    ...
}
Copy after login

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:

  • Value Type (e.g., handler): Modifications to the receiver within the method do not affect the original instance.
  • Pointer Type (e.g., *GracefulServer): Changes made to the receiver persist in the original instance.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template