Home > Backend Development > Golang > How to define methods for custom types in Golang?

How to define methods for custom types in Golang?

WBOY
Release: 2024-06-03 11:08:57
Original
1077 people have browsed it

In Go, you can define methods for custom types, that is, method receivers. Simply define the receiver type, method name, and parameters to add behavior for a specific type.

如何在 Golang 中为自定义类型定义方法?

#How to define methods for custom types in Go?

In Go, you can add methods to custom types just like you add methods to built-in types. This is called a method receiver. By defining a receiver, you can add behavior specific to a custom type.

Define a receiver method

To define a receiver method, use the following syntax:

func ( receiverType ) methodName( arguments ) returnType
Copy after login

Where:

  • receiverType is the custom type that defines the method.
  • methodName is the name of the method.
  • arguments are the parameters of the method (optional).
  • returnType is the return value type of the method (optional).

Practical case

The following example shows how to define a FullName method for the Person custom type:

type Person struct {
    firstName  string
    lastName   string
}

// 定义接收器方法
func (p Person) FullName() string {
    return fmt.Sprintf("%s %s", p.firstName, p.lastName)
}

func main() {
    person := Person{firstName: "John", lastName: "Doe"}
    fmt.Println(person.FullName()) // 输出:"John Doe"
}
Copy after login

Other notes

  • The receiver type must be a custom type (structure, interface, alias, etc.).
  • There must be a space between the method name and the receiver type.
  • The receiver type can be a value type or a pointer type.
  • The receiver type must be the same as the type declared in the package to which the method belongs.

The above is the detailed content of How to define methods for custom types in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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