Skip to content

Instantly share code, notes, and snippets.

@kamatama41
Last active December 26, 2016 02:38
Show Gist options
  • Save kamatama41/6e25dae3ece8f382da98 to your computer and use it in GitHub Desktop.
Save kamatama41/6e25dae3ece8f382da98 to your computer and use it in GitHub Desktop.
Golang pointer test.
package main
import "fmt"
type Vertex struct {
X, Y int
}
func changeImmutable(v Vertex) {
v.X = 123
v.Y = 456
}
func changeMutable(v *Vertex) {
v.X = 123
v.Y = 456
}
func main() {
v1 := Vertex{1, 2}
v2 := v1
v3 := &v1
fmt.Println(v1, v2, v3)
// v1のフィールドを変更するとポインタのデータも変更される
v1.X = 100
fmt.Println(v1, v2, v3)
// v2のフィールドを変更してもv1, v3は変更されない
v2.X = 999
fmt.Println(v1, v2, v3)
// オブジェクトをメソッドに渡しても元のデータは変更されない
changeImmutable(v1)
fmt.Println(v1, v2, v3)
// オブジェクトのポインタを渡すと変更される
changeMutable(v3)
fmt.Println(v1, v2, v3)
}
// result
//{1 2} {1 2} &{1 2}
//{100 2} {1 2} &{100 2}
//{100 2} {999 2} &{100 2}
//{100 2} {999 2} &{100 2}
//{123 456} {999 2} &{123 456}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment