Last active
November 21, 2019 09:07
-
-
Save Fullstop000/1f1c3148a0aa9fdd2425dcddd4c0253b to your computer and use it in GitHub Desktop.
Something about pointer and value in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Test struct { | |
A int | |
} | |
func testFn(a Test) Test { | |
return a | |
} | |
func main() { | |
a := Test{ | |
A: 1, | |
} | |
b := testFn(a) | |
c := Test{ | |
A: 1, | |
} | |
d := a // copy inner with a new pointer | |
d.A = 4 | |
fmt.Printf("%p, %p, %p, %p \n", &a, &b, &c, &d) | |
fmt.Println(a) | |
fmt.Println(d) | |
m := make(map[Test]int) | |
m[a] = 1 | |
m[c] = 2 // hash only care about the inner content | |
fmt.Println(m) | |
e := &a | |
f := e | |
fmt.Printf("%p, %p \n", &e, &f) | |
e.A = 4 // auto deref | |
fmt.Println(a) | |
fmt.Println(f) // auto deref | |
} | |
// 0x40e020, 0x40e024, 0x40e028, 0x40e02c | |
// {1} | |
// {4} | |
// map[{1}:2] | |
// 0x40c140, 0x40c148 | |
// {4} | |
// &{4} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment