The value and address of method in golang

    In golang, the form of struct method is as follows:

    func (r ReceiverType) funcName(parameters) (results)

    If you want to modify the value of a struct member, its ReceiverType must be in the form of struct* when the method is defined. If ReceiverType is struct, the values ​​of struct members cannot be changed.

    Without further ado, code verification:

package main

import (
    "fmt"
)

type tag struct {
    value int32
}

func (_tag tag) Change() {
    _tag.value = int32(987)
}

type tag2 struct {
    value int32
}

func (_tag *tag2) Change2() {
    _tag.value = int32(987)
}

func main() {
    _tag := new(tag)
    _tag.value = 123 
    _tag.Change()
    fmt.Println(_tag)
    _tag.Change()
    fmt.Println(_tag)

    _tag2 := tag2{41}
    _tag2.Change2()
    fmt.Println(_tag2)
    _tag2.Change2()
    fmt.Println(_tag2)
}

   In the main function above, the object _tag in the first code is in the form of *tag, but its method Change cannot change its value. The object _tag in the second piece of code is in the form of *ag, but its method Change can change its value.

    If anyone is interested, I'll tell you more.

    The first parameter of method in golang is its ReceiverType, while the method of method in C-based languages ​​such as c++ and its similar language java defaults to class* this. In other words, there are two methods in golang: passing object value and passing object address, while C-series languages ​​​​mandatory require passing the address of the object.

     That makes it understandable, right?

Guess you like

Origin blog.csdn.net/menggucaoyuan/article/details/43056261