传结构体参数

package main

import "fmt"

type coordinate struct {
	x int
	y int
}

func change1(c coordinate)  {
	c.x = 10
}

func change2(c *coordinate)  {
	c.x = 30
 大专栏  传结构体参数}

func main() {
	c := coordinate{20, 30}
	change1(c)
	fmt.Println(c.x)	//20

	change2(&c)
	fmt.Println(c.x)	//30
}

从上例可以看到,当传入结构体值时,对结构体内部类型的修改不影响原来结构体的值。

但是,需要注意的是,如果结构体中包含引用类型,即使是传递结构体值,对结构体内引用类型的修改仍会影响原来的结构体,因为引用类型的传值本质上是共享底层数据的。

猜你喜欢

转载自www.cnblogs.com/sanxiandoupi/p/11711156.html