go - 如何在 GO 中逐字初始化多层嵌套结构?

标签 go struct composite-literals

<分区>

我正在尝试在 GO 中逐字初始化以下结构:

这是结构:

type tokenRequest struct {
    auth struct {
        identity struct {
            methods  []string
            password struct {
                user struct {
                    name   string
                    domain struct {
                        id string
                    }
                    password string
                }
            }
        }
    }
}

这是我的代码:

req := &tokenRequest{
    auth: struct {
        identity: struct {
            methods: []string{"password"},
            password: {
                user: {
                    name: os.Username,
                    domain: {
                        id: "default",
                    },
                    password: os.Password,
                },
            },
        },
    },
}

https://play.golang.org/p/e8Yuk-37_nN

我可以在不单独定义所有嵌套结构的情况下进行初始化吗(即 authidentitypassworduser )

谢谢。

最佳答案

如果你有匿名的、未命名的结构类型,你只能在重复结构定义的情况下用复合文字初始化它们。这很不方便。

所以改用命名结构类型,这样你就可以像这样在复合文字中使用它们:

类型:

type domain struct {
    id string
}

type user struct {
    name     string
    domain   domain
    password string
}

type password struct {
    user user
}

type identity struct {
    methods  []string
    password password
}

type auth struct {
    identity identity
}

type tokenRequest struct {
    auth auth
}

然后初始化它(在 Go Playground 上尝试):

req := &tokenRequest{
    auth: auth{
        identity: identity{
            methods: []string{"password"},
            password: password{
                user: user{
                    name: os.Username,
                    domain: domain{
                        id: "default",
                    },
                    password: os.Password,
                },
            },
        },
    },
}

参见相关问题:Unexpected return of anonymous struct

关于go - 如何在 GO 中逐字初始化多层嵌套结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54125967/

相关文章:

c++ - 在 C++ 中添加互斥锁后结构中的赋值运算符

oop - 将其他pkg的类型嵌入到我的中,并通过字面量进行初始化

go - 信号 goroutines 在 channel 关闭时停止

go - panic : runtime error: index out of range processing file

xml - 使用 Go 解析 XML 文件

c - 双重释放或腐败(fasttop)

go - 如何在没有所有这些级联错误圣诞树的情况下编写干净的代码?

c++ - 从文本文件/XML 文件创建 C++ 类

go - 当将新结构体重新分配给变量时,golang 是否会分配新内存?

go - 了解go复合文字