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

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

Handle "Slice Struct" properly? (golang)

问题

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

package main

import "fmt"

type Slicestruct []struct {
	num      []int
	emptynum []int
}

func main() {
	slicestruct := &Slicestruct{
		{[]int{1, 2, 3}, []int{}},
		{[]int{4, 5, 6}, []int{}},
	}

	// 可以工作:
	fmt.Println(slicestruct)

	// 不能工作:
	fmt.Println(slicestruct[0].num[0])

	// 不能工作:
	slicestruct[0].emptynum = append(slicestruct[0].emptynum, 99)
}

错误信息是:"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?

package main

import "fmt"

type Slicestruct []struct {
	num      []int
	emptynum []int
}

func main() {
	slicestruct := &Slicestruct{
		{[]int{1, 2, 3}, []int{}},
		{[]int{4, 5, 6}, []int{}},
	}

	// is working:
	fmt.Println(slicestruct)

	// isn't working:
	fmt.Println(slicestruct[0].num[0])

	// isn't working:
	slicestruct[0].emptynum = append(slicestruct[0].emptynum, 99)
}

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

答案1

得分: 0

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

(*slicestruct)[0]

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

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

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

英文:

You need to dereference the pointer before getting an element

(*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:

确定