Home  >  Article  >  Backend Development  >  Detailed explanation of methods in Go language

Detailed explanation of methods in Go language

藏色散人
藏色散人forward
2020-08-27 13:29:442767browse

The following column will introduce you to the understanding of methods in Go language from the Golang Tutorial column. I hope it will be helpful to friends in need!

Detailed explanation of methods in Go language

go method

Definition

Methods are those with special receiver parameters Function, that is, the method receiver between func and the method name.

func (s Student) GetName() string  {
    return s.name}func (s *Student) SetName(name string) {
    s.name = name}

We can call member methods whose receiver type is a pointer called pointer methods, and member methods whose receiver type is non-pointer called value methods.

When you need to modify the object, you must use a pointer (pass by reference), otherwise just declare the type as a literal (pass by value). Also avoid copying the value on every method call.

type Integer intfunc (a *Integer) Increase(i Integer) {
    *a = *a + i}func main() {
    var a Integer = 2
    var b Integer = 2
    //a.Increase(b)
    //(&a).Increase(b)
    (*Integer).Increase(&a, b)
    fmt.Println(a)}

This method does not belong to the Integer class, but to the pointer type pointing to Integer. When we call the method, the reason why we can call the Increase method directly on an instance is because the Go language compilation phase will automatically Convert a into the corresponding pointer type &a, so the actual calling code is (&a).Increase(b).

is actually syntax sugar

type A struct {
  name string}func (a A) Name() string {
  a.name = "Hi! " + a.name  return a.name}func main() {
  a := A{name: "test"}

  fmt.Println(a.Name())

  fmt.Println(A.Name(a))}

a.Name() is actually the syntax of A.Name(a) Sugar, variable a is the so-called method receiver.

func NameOfA(a A) string {
  a.name = "Hi! " + a.name  return a.name}func main() {
  t1 := reflect.TypeOf(A.Name)
  t2 := reflect.TypeOf(NameOfA)

  fmt.Println(t1 == t2)// true}

The function type in the go language is only related to parameters and return values, so the equality of these two types can prove that the method is essentially an ordinary function, and the receiver is the implicit first parameter.

The above is the detailed content of Detailed explanation of methods in Go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete