匿名嵌套结构的用法

huangapple go评论98阅读模式
英文:

anonymous nested struct usage

问题

我之前问过这个问题并删除了它,但我还是不明白。我尝试了一切但仍然出错。我该如何使用这个结构体,或者我做错了什么?

type Unit struct{
	category struct{
		name string
	}
}
英文:

I've asked this question before and deleted it. but I don't understand. I tried everything but still getting error. how can i use this struct. or am i doing it wrong

type Unit struct{
	category struct{
		name string
	}
}

答案1

得分: 3

执行以下操作:

var unit = Unit{
    category: {
        name: "foo",
    },
}

不起作用,因为语言规范规定,在使用复合字面值初始化结构的字段时,必须指定类型。例如,嵌套结构、映射或切片等。


由于category的类型是一个未命名的复合类型,为了初始化该字段,必须重复未命名复合类型的定义。

type Unit struct{
    category struct{
        name string
    }
}

var unit = Unit{
    category: struct{
        name string
    }{
        name: "foo",
    },
}

或者,不要使用匿名结构。

type Category struct {
    name string
}

type Unit struct{
    category Category
}

var unit = Unit{
    category: Category{
        name: "foo",
    },
}

如果你想在声明该结构的包之外使用该结构,你必须导出其字段。

type Category struct {
    Name string
}

type Unit struct{
    Category Category
}

// ...

var unit = mypkg.Unit{
    Category: mypkg.Category{
        Name: "foo",
    },
}
英文:

Doing the following:

var unit = Unit{
    category: {
        name: "foo",
    },
}

will NOT work because the language specification says that you MUST specify the type when initializing a struct's field with a composite literal value. E.g. a nested struct, or a map, or a slice, etc.


Since category's type is an unnamed composite type, to initialize the field you MUST repeat the unnamed composite type's definition.

type Unit struct{
    category struct{
        name string
    }
}

var unit = Unit{
    category: struct{
        name string
    }{
        name: "foo",
    },
}

Alternative, do not use anonymous structs.

type Category struct {
    name string
}

type Unit struct{
    category Category
}

var unit = Unit{
    category: Category{
        name: "foo",
    },
}

And if you want to use this struct outside of the package in which it is declared you MUST export its fields

type Category struct {
    Name string
}

type Unit struct{
    Category Category
}

// ...

var unit = mypkg.Unit{
    Category: mypkg.Category{
        Name: "foo",
    },
}

huangapple
  • 本文由 发表于 2022年10月5日 21:44:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/73961325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定