简体   繁体   English

golang中的“复合文字中的缺少类型”

[英]“missing type in composite literal” in golang

Given these structs: 鉴于这些结构:

type InitRequest struct {
    ListenAddr      string
    ForceNewCluster bool
    Spec            Spec
}

type Spec struct {
    Annotations

    AcceptancePolicy AcceptancePolicy    `json:",omitempty"`
    //...
}

type AcceptancePolicy struct {
    Policies []Policy `json:",omitempty"`
}

type Policy struct {
    Role       NodeRole
    Autoaccept bool
    Secret     *string `json:",omitempty"`
}

This code doesn't compile, exiting on that line with missing type in composite literal . 该代码无法编译,在该行上以复合文字中的缺少类型退出。 Followed Go, Golang : array type inside struct, missing type composite literal , but same error with: 跟随Go,Golang:结构内部的数组类型,缺少复合文字 ,但是相同的错误:

swarm, err := cli.SwarmInit(context.Background(), swarm.InitRequest{
    ListenAddr:      "0.0.0.0:2377",
    ForceNewCluster: true,
    Spec: {
        AcceptancePolicy: {
            Policies: []Policy{
                Policy: {
                    Role:       "manager",
                    Autoaccept: true,
                },
            },
        }, // here
    },
})

Any hint will be very helpful, thanks! 任何提示都会非常有帮助,谢谢!

I identified a few issues with your code: 我发现您的代码存在一些问题:

  1. Your Policies field in AcceptancePolicy is a slice not a map AcceptancePolicy中的“您的政策”字段是切片而不是地图
  2. You didn't specify the types of the AcceptancePolicy or the Spec . 您没有指定AcceptancePolicySpec的类型。
  3. You're naming a variable the same as the import package. 您要为变量命名与导入包相同。
  4. Role is a NodeRole , not a string RoleNodeRole ,而不是字符串

Here's your code with the above fixes implemented: 这是实现了上述修复的代码:

mySwarm, err := cli.SwarmInit(context.Background(), swarm.InitRequest{
    ListenAddr:      "0.0.0.0:2377",
    ForceNewCluster: true,
    Spec: swarm.Spec{
        AcceptancePolicy: swarm.AcceptancePolicy{
            Policies: []swarm.Policy{
                {
                    Role:       some.conversion.to.NodeRole("manager"),
                    Autoaccept: true,
                },
            },
        }, // here
    },
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM