数组中的引用类型

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

Reference type in an array

问题

看一下下面的代码片段:

// 准备一些要插入模板的数据。
type Recipient struct {
    Name, Gift string
    Attended   bool
}
var recipients = []Recipient{
    {"姨妈米尔德", "骨瓷茶具", true},
    {"叔叔约翰", "麻布裤子", false},
    {"表弟罗德尼", "", false},
}

我创建了一个具有一些属性的结构体。然后创建了一个 Recipient 类型的切片。切片 recipients 里面是值类型还是引用类型?

看起来是值类型。

英文:

Look at the following code snippet

// Prepare some data to insert into the template.
type Recipient struct {
	Name, Gift string
	Attended   bool
}
var recipients = []Recipient{
	{"Aunt Mildred", "bone china tea set", true},
	{"Uncle John", "moleskin pants", false},
	{"Cousin Rodney", "", false},
}

I create a struct with some properties. After create a slice with Recipient type. Does slice recipients keeps value or reference type inside?

It seems to be value type.

答案1

得分: 2

一个切片实际上是指向数组的一部分的指针(参见slice的用法和内部原理),所以和数组一样,切片的元素是指定类型的值。

英文:

A slice is in fact a (kind of) pointer to a portion of an array (see slice usage and internals), so as for arrays, items are values of the specified type.

答案2

得分: 2

它会保留你声明的切片类型。在你的情况下,你声明为[]Recipient,所以它会将数据保存为值。

如果你将切片声明为[]*Recipient,那么它将保存引用(*Recipient),而不是Recipient的值。

英文:

It keeps whatever you declared your slice to be. In your case, you declared as []Recipient, so it will keep the data as value.

If you declare a slice as []*Recipient, then it will hold references (*Recipient), not Recipient values.

huangapple
  • 本文由 发表于 2014年7月27日 22:22:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/24981899.html
匿名

发表评论

匿名网友

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

确定