简体   繁体   中英

“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:

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
  2. You didn't specify the types of the AcceptancePolicy or the Spec .
  3. You're naming a variable the same as the import package.
  4. Role is a NodeRole , not a string

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
    },
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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