在Golang中,结构体的变量赋值是按引用传递还是按值传递呢?

huangapple go评论85阅读模式
英文:

pass by reference or by value in variable assignment of struct, Golang

问题

type temp struct{
val int
}

variable1 := temp{val:5} // 1
variable2 := &temp{val:6} // 2

在2中,引用被存储在variable2中。

在1中,是否进行了复制操作?或者variable1也指向相同的内存部分?还是与temp{val:5}有不同的内存部分?

英文:
type temp struct{
   val int
}

variable1 := temp{val:5}  // 1
variable2 := &temp{val:6} // 2

In 2, the reference is stored in the variable2.

In 1, does the copy operation is taking place? Or variable1 is also pointed to the same memory portion? or does have a different memory portion than temp{val:5} have?

答案1

得分: 1

temp{val:5} 是一个复合字面量,它创建了一个类型为 temp 的值。

在第一个示例中,你使用了短变量声明,它等价于

var variable1 = temp{val: 5}

这里创建了一个变量 (variable1),它被初始化为 temp{val: 5} 的值。

在第二个示例中,你获取了一个复合字面量的地址。这确实创建了一个变量,该变量被初始化为字面量的值,并且该变量的地址将成为表达式的结果。这个指针值将被赋给变量 variable2

规范:复合字面量

> 获取复合字面量的地址会生成一个指向用字面量的值初始化的唯一变量的指针。

英文:

temp{val:5} is a composite literal, it creates a value of type temp.

In the first example you used a short variable declaration, which is equivalent to

var variable1 = temp{val: 5}

There is a single variable created here (variable1) which is initialized with the value temp{val: 5}.

In the second example you take the address of a composite literal. That does create a variable, initialized with the literal's value, and the address of this variable will be the result of the expression. This pointer value will be assigned to the variable variable2.

Spec: Compositle literals:

> Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.

huangapple
  • 本文由 发表于 2022年3月8日 20:50:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/71395367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定