How do I print the pointer value of a Go object? What does the pointer value mean?

后端 未结 5 1378
野的像风
野的像风 2020-12-12 11:24

I am just playing around with Go and do not yet have a good mental model of when structs are passed by value or by reference.

This may be a very dumb question but I

5条回答
  •  情歌与酒
    2020-12-12 12:15

    In Go, arguments are passed by value.

    package main
    
    import "fmt"
    
    type SomeStruct struct {
        e int
    }
    
    // struct passed by value
    func v(v SomeStruct) {
        fmt.Printf("v: %p %v\n", &v, v)
        v.e = 2
        fmt.Printf("v: %p %v\n", &v, v)
    }
    
    // pointer to struct passed by value
    func p(p *SomeStruct) {
        fmt.Printf("p: %p %v\n", p, *p)
        p.e = 2
        fmt.Printf("p: %p %v\n", p, *p)
    }
    
    func main() {
        var s SomeStruct
        s.e = 1
        fmt.Printf("s: %p %v\n", &s, s)
        v(s)
        fmt.Printf("s: %p %v\n", &s, s)
        p(&s)
        fmt.Printf("s: %p %v\n", &s, s)
    }
    

    Output:

    s: 0xf800000040 {1}
    v: 0xf8000000e0 {1}
    v: 0xf8000000e0 {2}
    s: 0xf800000040 {1}
    p: 0xf800000040 {1}
    p: 0xf800000040 {2}
    s: 0xf800000040 {2}
    

提交回复
热议问题