Home >Backend Development >Golang >How to create golang method?

How to create golang method?

WBOY
WBOYOriginal
2024-04-26 08:06:02377browse

Steps to create a Go method: 1. Define the method syntax: func (receiver_type) method_name (parameters) return_type; 2. Call the method: instance_of_struct_type.method_name (arguments).

如何创建 golang 方法?

How to create a Go method

Define a method

In Go, a method is a function bound to a struct type. To create a method in a struct type, use the following syntax:

func (receiver_type) method_name(parameters) return_type

where

  • receiver_type is the struct type to which the method belongs.
  • method_name is the name of the method.
  • parameters is the list of parameters accepted by the method.
  • return_type is the type returned by the method.

Example

Create a Person structure with a getName method:

type Person struct {
    name string
}

func (p Person) getName() string {
    return p.name
}

Call method

To call a method, use the following syntax:

instance_of_struct_type.method_name(arguments)

where

  • instance_of_struct_type is the instance of the structure on which the method is to be called.
  • method_name is the name of the method to be called.
  • arguments are the parameters to be passed to the method.

Practical Case

Consider a web application that manages a list of users. We can create a User structure to represent the user, which contains the getName and setName methods:

type User struct {
    name string
}

func (u *User) getName() string {
    return u.name
}

func (u *User) setName(name string) {
    u.name = name
}

We can use these methods to retrieve And modify the user's name:

user := &User{name: "John Doe"}
fmt.Println(user.getName()) // 输出:"John Doe"

user.setName("Jane Doe")
fmt.Println(user.getName()) // 输出:"Jane Doe"

The above is the detailed content of How to create golang method?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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