简体   繁体   中英

Unable to initialise embedded struct

I have the following structs declared in packageA

type FlagSkel struct {
    Name    string
    Short   string
    HelpMsg string
}

type FlagString struct {
    Value        string
    DefaultValue string
}

type CompositeFlagString struct {
    FlagSkel
    FlagString
}

In another package, I am trying to initialise (outside any function) a var of the later type as follows:

var Name = packageA.CompositeFlagString{
    FlagSkel: {
        Name:    "name",
        Short:   "",
        HelpMsg: "Something here",
    },
    FlagString: {
        DefaultValue: "",
    },
}

However vscode compiler shows me the attached error

在此处输入图像描述

What am I doing wrong?

You need to specify the type for the struct literals:

packageA.CompositeFlagString{
    FlagSkel: packageA.FlagSkel{
        Name:    "name",
        Short:   "",
        HelpMsg: "Something here",
    },
    FlagString: packageA.FlagString{
        DefaultValue: "",
    },
}

You missed to set the type of your inner structs you want to create. your variable initialisation should be:

var Name = packageA.CompositeFlagString{
    FlagSkel: packageA.FlagSkel {
        Name:    "name",
        Short:   "",
        HelpMsg: "Something here",
    },
    FlagString: packageA.FlagString {
        DefaultValue: "",
    },
}

If you change this, it should work.

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