package main
type Inner struct {
x int
}
type Outer struct {
Inner
}
func main() {
x := Inner{1}
y := (Outer)(x) // cannot convert x (type Inner) to type Outer
}
conversions 上的 go 规范部分声称
A non-constant value x can be converted to type T in any of these cases: ... Ignoring struct tags (see below), x's type and T have identical underlying types. ...
关于 type identity 的部分说:
Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags.
据我了解,Inner
和 Outer
都有一个字段 x
,它是一个 int
。那么,为什么我不能将 Outer
转换为 Inner
?
我最终发现我可以使用 x.Inner
,但这花了我一段时间,所以我很好奇为什么(在我看来)更明显的方法被禁止。
最佳答案
Outer
没有字段 x
。它有一个字段 Inner
,它有一个字段 x
。当访问 .x
时,选择器 (.
) 会自动从存在这样一个 x
的最浅层提升一个嵌入字段。
请参阅 Selectors 上的规范
关于go - 为什么不能将结构转换为嵌入式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082687/