[GO] Pass by reference

func changeName(name *string) {
	*name = strings.ToUpper(*name)
}

// Coordinates
type Coordinates struct {
	X, Y float64
}

func main() {
	name := "Elvis"
	changeName(&name)
	fmt.Println(name) // ELVIS

	var c = Coordinates{X: 10, Y: 20}
	// If pass c by value, then it won't modify c
	coordAddress := c
	coordAddress.X = 200
	fmt.Println(coordAddress) // {200 20}
	fmt.Println(c)            // {10 20}

	// If pass c by refernece, then it will modify c as well
	coordAddress2 := &c
	coordAddress2.X = 200
	fmt.Println(*coordAddress2) // {200 20}
	fmt.Println(c)              // {200 20}
}

 

posted @ 2022-09-06 01:56  Zhentiw  阅读(13)  评论(0编辑  收藏  举报