【问题标题】:How Can I Access `struct` 's Field in a New `type` of That `struct` slice?如何在该 `struct` 切片的新`type` 中访问`struct` 的字段?
【发布时间】:2020-07-19 10:05:20
【问题描述】:

代码是这样的

package main

import "fmt"

type Hello struct {
    ID  int
    Raw string
}

type World []*Hello

func HelloWorld() *World {
    return &World{
        {
            ID:  1,
            Raw: "asd",
        },
        {
            ID:  2,
            Raw: "jkf",
        },
    }
}

func main() {
    something := HelloWorld()

    // What I want to achieve...
    fmt.Println(something[0].Raw) // This should return `"asd"`.
}

但我收到了这个错误 ---> ./prog.go:29:23: invalid operation: something[0] (type *World does not support indexing)。如何从something 获取Raw

【问题讨论】:

标签: go struct types


【解决方案1】:

使用(*something)[0].Raw,因为somethingWorld类型的指针。

我们需要使用 * 运算符,也称为解引用运算符,如果将它放在指针变量之前,它会返回该内存中的数据。

fmt.Println((*something)[0].Raw) 

【讨论】:

  • 哦新手错误对不起:(。我会尽快接受你的回答。
猜你喜欢
  • 2012-03-08
  • 2022-11-02
  • 1970-01-01
  • 2013-09-24
  • 2020-09-07
  • 2021-09-15
  • 2015-07-06
  • 2014-10-29
  • 1970-01-01
相关资源
最近更新 更多