![](/img/trans.png)
[英]What is the difference between 'struct (*)[]' and 'struct *[]'?
[英]What's the difference between []struct{} and []*struct{}?
下面有什么区别?
type Demo struct {s string}
func getDemo1()([]*Demo) // 1
func getDemo2()([]Demo) // 2
getDemo1
和getDemo2
之间有什么内存差异吗?
尽管我有更好的判断力,只是将OP发送给巡回演出和文档/说明,我还是要回答这个问题。 主要是因为:
getDemo1和getDemo2之间有什么内存差异吗?
这个特定问题的答案取决于您如何利用切片。 Go是按值传递,因此传递结构值会复制它们。 例如,考虑以下示例。
https://play.golang.org/p/VzjYXwUy0EI
d1 := getDemo1()
d2 := getDemo2()
for _, v := range d1 {
// v is of type *Demo, so this modifies the value in the slice
v.s = "same"
}
fmt.Println(d1)
for _, v := range d2 {
// v is of type Demo, and is a COPY of the struct in the slice, so the original is not modified
v.s = "same"
}
关于内存问题,显然使用*Demo
,它返回范围内的指针的副本(有效地是uint64
),而不是返回Demo
的副本(整个struct及其所有字段),将使用较少的内存。 但是 ,您仍然可以直接索引到数组以避免复制,除非您在切片中传递单个项目。
也就是说,通过切片本身,这两种类型的开销没有区别。 切片是数组的抽象,传递过来的切片本身仅仅是切片头,无论切片包含哪种类型,它都将是相同的内存占用量。
顺便说一句,在[]Demo
的情况下修改值的范例是:
for i, _ := range d2 {
d2[i].s = "same"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.