匿名嵌套结构的用法

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

anonymous nested struct usage

问题

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

  1. type Unit struct{
  2. category struct{
  3. name string
  4. }
  5. }
英文:

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

  1. type Unit struct{
  2. category struct{
  3. name string
  4. }
  5. }

答案1

得分: 3

执行以下操作:

  1. var unit = Unit{
  2. category: {
  3. name: "foo",
  4. },
  5. }

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


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

  1. type Unit struct{
  2. category struct{
  3. name string
  4. }
  5. }
  6. var unit = Unit{
  7. category: struct{
  8. name string
  9. }{
  10. name: "foo",
  11. },
  12. }

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

  1. type Category struct {
  2. name string
  3. }
  4. type Unit struct{
  5. category Category
  6. }
  7. var unit = Unit{
  8. category: Category{
  9. name: "foo",
  10. },
  11. }

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

  1. type Category struct {
  2. Name string
  3. }
  4. type Unit struct{
  5. Category Category
  6. }
  7. // ...
  8. var unit = mypkg.Unit{
  9. Category: mypkg.Category{
  10. Name: "foo",
  11. },
  12. }
英文:

Doing the following:

  1. var unit = Unit{
  2. category: {
  3. name: "foo",
  4. },
  5. }

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.

  1. type Unit struct{
  2. category struct{
  3. name string
  4. }
  5. }
  6. var unit = Unit{
  7. category: struct{
  8. name string
  9. }{
  10. name: "foo",
  11. },
  12. }

Alternative, do not use anonymous structs.

  1. type Category struct {
  2. name string
  3. }
  4. type Unit struct{
  5. category Category
  6. }
  7. var unit = Unit{
  8. category: Category{
  9. name: "foo",
  10. },
  11. }

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

  1. type Category struct {
  2. Name string
  3. }
  4. type Unit struct{
  5. Category Category
  6. }
  7. // ...
  8. var unit = mypkg.Unit{
  9. Category: mypkg.Category{
  10. Name: "foo",
  11. },
  12. }

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:

确定