首页 > 解决方案 > 获取未定义的嵌套结构属性

问题描述

(之前链接的“答案”没有回答这个问题。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",
    },
}

标签: gostruct

解决方案


尝试将 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")
}

如果您想了解嵌套结构,这可能会有所帮助


推荐阅读