为什么不能将结构转换为嵌入式类型 [英] Why can't a struct be converted to an embedded type

查看:58
本文介绍了为什么不能将结构转换为嵌入式类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 程序包主要输入内部结构{x int}输入外部结构{内}func main(){x:=内部{1}y:=(外部)(x)//无法将x(内部类型)转换为外部类型} 

关于转化的go spec部分声称

在以下任何一种情况下,非恒定值x都可以转换为类型T:...忽略struct标记(见下文),x的类型和T具有相同的基础类型....

关于类型身份的部分说:

如果两个struct类型具有相同的字段序列,并且对应的字段具有相同的名称,相同的类型和相同的标记,则它们是相同的.

据我了解,内部外部都有一个单独的字段 x ,即 int .那么为什么不能将外部转换为内部?

我最终发现我可以使用 x.Inner ,但是花了我一段时间,所以我很好奇为什么不允许使用(我认为)更明显的方法.

解决方案

外部没有字段 x .它有一个字段 Inner ,有一个字段 x .当访问 .x 时,选择器(.)将自动从最浅的深度(其中存在 x 的位置)提升嵌入的字段.

请参见选择器

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
}

The go spec section on conversions claims that

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. ...

The section on type identity says:

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.

It is my understanding that both Inner and Outer have a single field x which is an int. So why can't I convert an Outer to an Inner?

I eventually figured out that I can use x.Inner, but it took me a while, so I'm curious why the (in my opinion) more obvious approach is disallowed.

解决方案

Outer does not have a field x. It has a field Inner, which has a field x. When accessing .x, the selector (.) will automatically promote an embedded field from the shallowest depth where there is such an x.

See the spec on Selectors

这篇关于为什么不能将结构转换为嵌入式类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆