go - 为什么不能将结构转换为嵌入式类型

标签 go type-conversion

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.

据我了解,InnerOuter 都有一个字段 x,它是一个 int。那么,为什么我不能将 Outer 转换为 Inner

我最终发现我可以使用 x.Inner,但这花了我一段时间,所以我很好奇为什么(在我看来)更明显的方法被禁止。

最佳答案

Outer 没有字段 x。它有一个字段 Inner,它有一个字段 x。当访问 .x 时,选择器 (.) 会自动从存在这样一个 x 的最浅层提升一个嵌入字段。

请参阅 Selectors 上的规范

关于go - 为什么不能将结构转换为嵌入式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082687/

相关文章:

arrays - 如何在 Go 中将错误数组转换为 JSON

c++ - 将 variant、vector<variant> 和 vector<vector<variant>> 转换为我选择的等效类型

c++ - 声明具有两种类型的变量 : "int char"

c# - 如何编写将分隔字符串转换为列表的通用扩展方法?

java - 将 char[] 转换为 byte[]

go - 如何读取固定数量的字节?

go - 为什么循环中分配后的ID为0?

sql - 如何为动态SQL查询创建结构?

macos - 当构建参数包含`-gcflags“all = -N -l”并在MacOS中导入net/http时,构建失败

c# - 如何在 C# 中将 FormatConvertedBitmap 转换为 Stream