【问题标题】:Handle "Slice Struct" properly? (golang)正确处理“切片结构”? (戈朗)
【发布时间】:2021-05-30 00:18:26
【问题描述】:

我创建了一个切片结构。 但是为什么我不能追加或输出值呢?

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)
}

错误信息是:“无效操作:slicestruct[0](类型*Slicestruct不支持索引)”

【问题讨论】:

    标签: go struct slice


    【解决方案1】:

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

    (*slicestruct)[0]
    

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

    这里有一个关于指向切片和数组的指针的相关问题:Pointer to slice and array

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

    【讨论】:

    • 有了你的解释我终于明白了。感谢您的帮助。
    猜你喜欢
    • 2020-02-20
    • 2021-11-04
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2015-02-21
    相关资源
    最近更新 更多