SoFunction
Updated on 2025-03-05

This article will help you understand the calls of methods in Go language

Preface

In the frontFamiliar with Go functions in one articleIn the article, the declaration of Go functions is introduced, and several forms of functions are such as anonymous functions, closures, custom types based on functions and detailed explanations of function parameters, etc. This article will introduce the method. The essence of the method is a function. While introducing the method, it will also compare the differences between it and the function.

method

In Go, we can define methods for any data type (except pointers or interfaces), and now let's take a look at the declarations and components of methods and what's different from functions.

type Person struct {
	age int
}

func (p *Person) SetAge(age int) error {
	if age < 0 {
		return ("Age cannot be less than 0")
	}
	 = age
	return nil
}

The above code defines a structurePerson, this structure contains aageAttribute, aSetAgeMethod, this method only works onPersonStructure. We can see that this method contains six parts:

  • 1. When declaring a method, you mustfuncStarting with the keyword, do you still remember the declaration of the function? It also starts with this keyword.
  • 2、receiverpart(p *Person)This part,GoChinese known asreceiverThe parameters inside are calledreceiverCompared with functions, the difference between methods and their declarations is that there is more of this part.
  • 3. Method name.GoIt is recommended to use camel naming. Like the naming rules of variables, method names with uppercase letters can be accessed outside the package, while lowercase letters can only be accessed inside the package.
  • 4. Parameter list The variables used in the method body are declared in the parameter list. The parameter list is behind the method name, wrapped in brackets, and multiple parameters are separated by commas.
  • 5. Return value list The return value is a result after the function is executed. The above code has only one return value. If there are multiple return values, it needs to be wrapped in brackets, and the return values ​​are separated by commas.
  • 6. Method body The method body is in the braces, and the specific implementation of the method is stored.

Method call

passVariable. Method name (parameter)call the method in a way. For example:

import (
	"errors"
	"fmt"
)

type Person struct {
	age int
}

func (p *Person) SetAge(age int) error {
	if age < 0 {
		return ("Age cannot be less than 0")
	}
	 = age
	return nil
}

func main() {
	person := Person{}
	err := (18)
	if err != nil {
		return
	}
	() // 18
}

Create apersonvariable, then callSetAgefunction.

Receiver parameter type selection

existReceiverIn part, we can bind value types or pointer types. When will these two types be used?

If the method body does not involve modifying the attribute value of the structure variable, use the value type

type Person struct {
        age int
}

func (p Person) GetAge() int {
        return 
}

forGetAgeThe method is to return age, and there is no operation to modify age, soreceiverPart, selectPersonType is OK.

If there is an operation to modify the attribute value of the structure variable in the method body, use the pointer type

type Person struct {
	age int
}

func (p *Person) SetAge(age int) error {
	if age < 0 {
		return ("Age cannot be less than 0")
	}
	 = age
	return nil
}

SetAgeIt involves the operation of modifying the attribute value of the structure, soreceiverSome use pointer type, through pointers, you can modify the variables pointed to.

Method constraints

GoThere are constraints on the location of method declarations. We cannot declare a type of method across packages. Based on this feature, we can find:

Cannot declare methods for basic data types

Because the location defined by the basic data type is not in the package we encoded.

Cannot declare methods for other packages in a type that can be crossed

This isGoas specified.

summary

This article introduces the declaration method, components and differences between Go methods and their functions, and points out thatReceiverThe selection of parameter types in different scenarios is finally introducedGoThe manifestation of method constraints.

This is the article about this article about how to learn about the call of method in Go. For more relevant Go language method content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!