go - 获取未定义的嵌套结构属性
问题描述
(之前链接的“答案”没有回答这个问题。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",
},
}
解决方案
尝试将 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")
}
如果您想了解嵌套结构,这可能会有所帮助。
推荐阅读
- css - SASS 选择器附加函数,带有多个带空格的选择器
- php - 如何从php中的多维数组中删除空数组?
- c++ - 将文本文件中的文本存储到六个不同的向量中 (C++)
- java - 如何覆盖基于 Java 的 Web 应用程序中重复的 http 缓存标头?
- java - Spring Reactor 和服务器发送事件连接问题
- android - 如何阻止用户访问锁定屏幕中的状态栏和导航栏?
- python - 函数'对象没有属性'对象
- javascript - 反应没有表单组件的输入表单?
- javascript - 如何从 Google 表格运行 Google Doc ID 循环
- power-automate - 无法创建流