Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 正在获取嵌套结构属性的未定义_Go_Struct - Fatal编程技术网

Go 正在获取嵌套结构属性的未定义

Go 正在获取嵌套结构属性的未定义,go,struct,Go,Struct,(前面链接的“答案”没有回答此问题。stackoverflow.com/questions/24809235/initialize-a-nested-struct。除非您能提供明确的答案,否则请不要关闭此问题。) 在这个嵌套结构示例testJSON中,我得到一个错误Foo未定义 对于Foo属性,不确定使用TestStruct赋值的正确方法是什么 // TestStruct a test struct type TestStruct struct { Foo struct {

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

在这个嵌套结构示例
testJSON
中,我得到一个错误
Foo未定义

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

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

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

试着让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")
}

如果您愿意。

错误是准确的:
Foo
未定义。您在此处使用的
Foo
文本中没有可以引用的
type Foo
。您有一个字段
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文档以获取一些深度嵌套的字段时,这可能很有用。

代码中没有
类型Foo struct{…
声明,因此未定义。您有的是类型为匿名结构的字段Foo。因此,尝试执行
Foo{}
初始化匿名结构会导致编译器错误。因此,请使用声明的类型而不是匿名类型。如果必须使用匿名结构,则必须对其进行初始化,即
Foo:struct{Thing string}{Thing:“this Thing…”
但正如您所看到的,这很难看且冗长,因此,再次使用命名类型。最后一种方法是,使用匿名,但将字段值设置为文本的“外部”,即
var testJSON=TestStruct{};testJSON.Foo.Thing=“test Thing”
。谢谢@mkopriva。但是我的示例的声明方式与上所述的相同。有什么区别吗?你不是在文章中这样做:。区别在于你在做
Foo:Foo{…}
而他们在做
Foo:struct{Thing string}{…}
查看您的尝试的有效版本:将其与您的进行比较,您应该会看到差异,以防还不清楚。