英文:
How to modify a slice element which is a struct in golang?
问题
你有一个包含结构体的 Golang 切片,并且想要修改其中的一个条目。
type Type struct {
value int
}
func main() {
s := []Type{{0}, {0}}
// 打印 [{0} {0}]
fmt.Println(s)
firstEntry := s[0]
firstEntry.value = 5
// 仍然打印 [{0} {0}]
fmt.Println(s)
}
使用方括号操作符并修改其返回值并不会改变切片本身。
有什么推荐的方法可以修改切片中的条目?
英文:
You have a golang slice of structs and you would like to change one entry in there.
type Type struct {
value int
}
func main() {
s := []Type{{0}, {0}}
// Prints [{0} {0}]
fmt.Println(s)
firstEntry := s[0]
firstEntry.value = 5
// Also prints [{0} {0}]
fmt.Println(s)
}
https://play.golang.org/p/32tpcc3-OD
Using the brackets operator and modifying its return does not change the slice itself.
What is the recommended way of doing this slice entry modification ?
答案1
得分: 41
尝试一下:
s[0].value = 5
这将访问切片的底层存储。另外,
p := &s[1]
p.value = 6
英文:
Try
s[0].value = 5
This gets to the backing store of the slice. Also
p := &s[1]
p.value = 6
答案2
得分: 6
你也可以直接获取切片元素的地址并对其进行解引用:
func main() {
s := []Type{{0}, {0}}
// 打印 [{0} {0}]
fmt.Println(s)
// 对切片元素的地址进行解引用
(&s[0]).value = 5
// 打印 [{5} {0}]
fmt.Println(s)
}
英文:
You can also take the address of the slice element directly and de-reference it:
func main() {
s := []Type{{0}, {0}}
// Prints [{0} {0}]
fmt.Println(s)
// De-reference the address of the slice element
(&s[0]).value = 5
// Prints [{5} {0}]
fmt.Println(s)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论