为嵌套的struct属性获取未定义

时间:2019-11-14 21:13:31

标签: go struct

(先前链接的“答案”不能回答该问题。stackoverflow.com/questions/24809235/initialize-a-nested-struct。除非您提供明确的答案,否则请不要关闭该问题。)

在此嵌套结构示例testJSON中,我遇到了一个错误Foo is undefined

https://play.golang.com/p/JzGoIfYPNjZ

对于TestStruct属性,不确定使用Foo分配值的正确方法是什么。

// TestStruct a test struct
type TestStruct struct {
    Foo struct {
        Thing string `json:Thing`
    } `json:Foo`
}

var testJSON = TestStruct{
    Foo: Foo{
        Thing: "test thing string",
    },
}

2 个答案:

答案 0 :(得分:0)

尝试将Foo设为自己的结构。

package main

import (
    "fmt"
)

// TestStruct a test struct
type TestStruct struct {
    // you have to make the Foo struct by itself
    Foo
}

type Foo struct {
    Thing string
}

var testJSON = TestStruct{
    Foo: Foo{
        Thing: "test thing string",
    },
}

func main() {
    fmt.Println("Hello, playground")
}

如果您想read about nested Structs, this might help

答案 1 :(得分:0)

错误是正确的:Foo 未定义。这里没有type Foo可以指代您在文字中使用Foo。您有一个 field Foo,但是它的类型是匿名类型struct { Thing string }。因此,要用文字填充该字段,您必须使用其正确的类型名称,它不是Foo,而是struct { Thing string }

var testJSON = TestStruct{
    Foo: struct {
        Thing string
    }{
        Thing: "test thing string",
    },
}

大多数开发人员都不喜欢使用他们实际上需要引用的类型来做这些冗长的操作,因此在这种情况下,他们将使用命名类型:

type TestStruct struct {
    Foo Foo `json:Foo`
}

type Foo struct {
    Thing string `json:Thing`
}

在这种情况下,您现有的创建代码会正常工作。匿名类型最常用于不需要引用的情况,即,反射是实例化类型的唯一方法。当您想将一些JSON解组到一个类型中,但又不想以编程方式创建该类型的实例时,就是这种情况。您甚至会看到未命名最外层类型的情况,例如:

type TestStruct struct {
    Foo struct {
        Thing string `json:Thing`
    } `json:Foo`
}

var testJSON = struct {
    Foo struct {
        Thing string `json:Thing`
    } `json:Foo`
}{}

json.Unmarshal(something, &testJSON)

fmt.Printf(testJSON.Foo.Thing)

当您想解组一个复杂的JSON文档只是为了获取一些深层嵌套的字段时,这很有用。

相关问题