"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What do the Brackets After `func` in Go Methods Indicate?

What do the Brackets After `func` in Go Methods Indicate?

Published on 2024-12-22
Browse:791

What do the Brackets After `func` in Go Methods Indicate?

Understanding Brackets After func in Go Methods

In Go, you may encounter brackets following a func keyword. These signify a method, not a function. Let's understand this feature with a specific example:

func (v Version) MarshalJSON() ([]byte, error) {
  return json.Marshal(v.String())
}

Here, we have a method named MarshalJSON attached to the Version struct type. The syntax:

  • (v Version): This part represents the method receiver. For methods, the first parameter is always the receiver value. Here, v represents an instance of the Version struct.
  • func: Indicates that this is a method.
  • MarshalJSON(): The method name, followed by its signature.

So, in this example, the MarshalJSON method of the Version struct converts its string representation to JSON.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3