登录
首页 >  Golang >  Go问答

嵌套结构属性未定义

来源:stackoverflow

时间:2024-03-30 22:54:32 466浏览 收藏

本篇文章向大家介绍《嵌套结构属性未定义》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

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

在此嵌套结构示例 testjson 中,我收到错误 foo is undefined

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

不确定在 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")
}

如果你想要read about nested Structs, this might help

到这里,我们也就讲完了《嵌套结构属性未定义》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>