处理 “Slice Struct” 是否正确?(golang)

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

Handle "Slice Struct" properly? (golang)

问题

我已经创建了一个Slice Struct。但为什么我不能追加或输出值?

  1. package main
  2. import "fmt"
  3. type Slicestruct []struct {
  4. num []int
  5. emptynum []int
  6. }
  7. func main() {
  8. slicestruct := &Slicestruct{
  9. {[]int{1, 2, 3}, []int{}},
  10. {[]int{4, 5, 6}, []int{}},
  11. }
  12. // 可以工作:
  13. fmt.Println(slicestruct)
  14. // 不能工作:
  15. fmt.Println(slicestruct[0].num[0])
  16. // 不能工作:
  17. slicestruct[0].emptynum = append(slicestruct[0].emptynum, 99)
  18. }

错误信息是:"invalid operation: slicestruct[0] (type *Slicestruct does not support indexing)"

英文:

I have created a Slice Struct.
But why can't I append or output values?

  1. package main
  2. import "fmt"
  3. type Slicestruct []struct {
  4. num []int
  5. emptynum []int
  6. }
  7. func main() {
  8. slicestruct := &Slicestruct{
  9. {[]int{1, 2, 3}, []int{}},
  10. {[]int{4, 5, 6}, []int{}},
  11. }
  12. // is working:
  13. fmt.Println(slicestruct)
  14. // isn't working:
  15. fmt.Println(slicestruct[0].num[0])
  16. // isn't working:
  17. slicestruct[0].emptynum = append(slicestruct[0].emptynum, 99)
  18. }

The error message is: "invalid operation: slicestruct[0] (type *Slicestruct does not support indexing)"

答案1

得分: 0

你需要在获取元素之前取消引用指针。

  1. (*slicestruct)[0]

因为你访问的是实际的切片,而不是指针。对于指向数组的指针(不是像这里的切片),这一步会自动完成。

这里有一个关于指向切片和数组的指针的相关问题:https://stackoverflow.com/questions/36242018/pointer-to-slice-and-array

或者,你可以在声明变量时去掉&,使其不是指针类型。在我们这里看到的简短示例中,没有必要使用指针。一般来说,指向切片类型的指针的合法用途很少见。

英文:

You need to dereference the pointer before getting an element

  1. (*slicestruct)[0]

Since it's the actual slice you're accessing an element from, not the pointer.
For pointers to arrays (not slices as you have here), this step would be done automatically.

Here's a related question about pointers to slices and arrays: https://stackoverflow.com/questions/36242018/pointer-to-slice-and-array

Alternatively, you can remove the & when declaring your variable to make it not a pointer type. In the short sample we've seen here, there's nothing to necessitate a pointer. In general, legitimate uses of pointers to slices types are rare.

huangapple
  • 本文由 发表于 2021年5月30日 08:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/67756664.html
匿名

发表评论

匿名网友

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

确定