英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论