这个问题的答案可能是“好吧,这就是Go的方式”,但我想了解以下行为背后的原因,即索引值类型的切片:
package main
import (
"fmt"
)
type S struct {
Data string
}
func main() {
s := []S{
{"first"},
{"second"},
{"third"},
}
// # 1
// This does not modify "s"
first := s[0]
first.Data = "something else"
fmt.Println(s)
// # 2
// ...but this does?
s[0].Data = "woah"
fmt.Println(s)
// # 3
// ...and this makes sense but feels inconsistent with the previous block
second := &s[1]
second.Data = "this makes sense"
fmt.Println(s)
}
我的问题是,为什么更新给定的切片编译但不编译?#2var element S = s[0]var element *S = s[0]
蓝山帝景
相关分类