在嵌套结构中的复合字面量中缺少类型。

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

missing type in composite literal in nested struct

问题

我有以下匿名结构体:

func wrapHal(selfHref string) interface{} {
	return struct {
		_links struct {
			self struct {
				href string
			}
		}
	}{
		_links: struct {
			self struct {
				href string
			}
		}{
			self: struct {
				href string
			}{
				href: selfHref,
			},
		},
	}
}

然而,在"this line"这一行,我得到了错误信息missing type in composite literal

如何修复它?在Go中是否可以初始化一个匿名嵌套结构体?

英文:

I have the following anonymous struct:

func wrapHal(selfHref string) interface{} {
	return struct {
		_links struct {
			self struct {
				href string
			}
		}
	}{
		_links: {self: {href: selfHref}}, # this line
	}
}

However, in "this line, " I get the error missing type in composite literal

How to fix it? It is possible to initiate a anonymous nested struct in Go?

答案1

得分: 2

要初始化一个匿名结构体,你需要先声明类型。你已经声明了根匿名结构体,但是对于每个嵌套的匿名结构体,你需要再次声明类型:

func wrapHal(selfHref string) interface{} {
	return struct {
		_links struct {
			self struct {
				href string
			}
		}
	}{
		_links: struct {
			self struct {
				href string
			}
		}{
			self: struct {
				href string
			}{
				href: "",
			},
		},
	}
}
英文:

To initialize an anonymous struct, you have to declare the type. You declared the root anonymous struct, but you need to do again for each nested anonymous struct:

func wrapHal(selfHref string) interface{} {
	return struct {
		_links struct {
			self struct {
				href string
			}
		}
	}{
		_links: struct {
			self struct {
				href string
			}
		}{
			self: struct {
				href string
			}{
				href: "",
			},
		},
	}
}

huangapple
  • 本文由 发表于 2022年7月23日 04:10:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/73085631.html
匿名

发表评论

匿名网友

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

确定