Last active
December 26, 2016 02:38
-
-
Save kamatama41/6e25dae3ece8f382da98 to your computer and use it in GitHub Desktop.
Golang pointer test.
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 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