下面有什么区别?
type Demo struct {s string}
func getDemo1()([]*Demo) // 1
func getDemo2()([]Demo) // 2
getDemo1
和getDemo2
在内存上有区别吗?
最佳答案
我要回答这个问题,尽管我的判断更好,只是将 OP 发送到导览和文档/规范。主要是因为:
Is there any memory difference between getDemo1 and getDemo2?
这个具体问题的答案取决于您如何使用 slice 。 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
(整个结构及其所有字段)将使用更少的内存。 但是,您仍然可以直接索引数组以避免复制,除非您传递 slice 中的单个项目。
也就是说,传递 slice 本身,这两种类型在开销上没有区别。 slice 是数组的抽象,传递的 slice 本身只是一个 slice header ,无论 slice 包含什么类型,它都会占用相同的内存。
顺便说一句,在 []Demo
的情况下修改值的范例是:
for i, _ := range d2 {
d2[i].s = "same"
}
关于pointers - []struct{} 和 []*struct{} 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52541624/