What is the difference between passing a struct and pointer of the struct, are they not both pointers?

后端 未结 2 1645
执念已碎
执念已碎 2021-02-02 14:20

For example

var myStructRef *Vertex
var myStruct Vertex
myStructRef = &Vertex{2, 3}
myStruct = Vertex{2, 3}

fmt.Println(myStructRef)
fmt.Println(myStruct)
c         


        
2条回答
  •  鱼传尺愫
    2021-02-02 14:56

    Passing struct to function argument makes copy of values. And passing pointer of struct doesn't. So passing struct can't update field value.

    package main
    
    import (
        "fmt"
    )
    
    type Foo struct {
        value int
    }
    
    func PassStruct(foo Foo) {
        foo.value = 1
    }
    
    func PassStructPointer(foo *Foo) {
        foo.value = 1
    }
    
    func main() {
        var foo Foo
    
        fmt.Printf("before PassStruct: %v\n", foo.value)
        PassStruct(foo)
        fmt.Printf("after PassStruct: %v\n", foo.value)
    
        fmt.Printf("before PassStructPointer: %v\n", foo.value)
        PassStructPointer(&foo)
        fmt.Printf("after PassStructPointer: %v\n", foo.value)
    }
    

    https://play.golang.org/p/AM__JwyaJa

提交回复
热议问题