How to modify a slice element which is a struct in golang?

huangapple go评论104阅读模式
英文:

How to modify a slice element which is a struct in golang?

问题

你有一个包含结构体的 Golang 切片,并且想要修改其中的一个条目。

  1. type Type struct {
  2. value int
  3. }
  4. func main() {
  5. s := []Type{{0}, {0}}
  6. // 打印 [{0} {0}]
  7. fmt.Println(s)
  8. firstEntry := s[0]
  9. firstEntry.value = 5
  10. // 仍然打印 [{0} {0}]
  11. fmt.Println(s)
  12. }

使用方括号操作符并修改其返回值并不会改变切片本身。

有什么推荐的方法可以修改切片中的条目?

英文:

You have a golang slice of structs and you would like to change one entry in there.

  1. type Type struct {
  2. value int
  3. }
  4. func main() {
  5. s := []Type{{0}, {0}}
  6. // Prints [{0} {0}]
  7. fmt.Println(s)
  8. firstEntry := s[0]
  9. firstEntry.value = 5
  10. // Also prints [{0} {0}]
  11. fmt.Println(s)
  12. }

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

尝试一下:

  1. s[0].value = 5

这将访问切片的底层存储。另外,

  1. p := &s[1]
  2. p.value = 6
英文:

Try

  1. s[0].value = 5

This gets to the backing store of the slice. Also

  1. p := &s[1]
  2. p.value = 6

答案2

得分: 6

你也可以直接获取切片元素的地址并对其进行解引用:

  1. func main() {
  2. s := []Type{{0}, {0}}
  3. // 打印 [{0} {0}]
  4. fmt.Println(s)
  5. // 对切片元素的地址进行解引用
  6. (&s[0]).value = 5
  7. // 打印 [{5} {0}]
  8. fmt.Println(s)
  9. }
英文:

You can also take the address of the slice element directly and de-reference it:

  1. func main() {
  2. s := []Type{{0}, {0}}
  3. // Prints [{0} {0}]
  4. fmt.Println(s)
  5. // De-reference the address of the slice element
  6. (&s[0]).value = 5
  7. // Prints [{5} {0}]
  8. fmt.Println(s)
  9. }

huangapple
  • 本文由 发表于 2016年12月14日 01:42:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41127380.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定