go refspec: 已定义/未定义类型的可赋值性

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

go refspec: assignability of defined/undefined types

问题

https://golang.org/ref/spec#Assignability中提到:

> 如果满足以下条件之一,值x可以分配给类型为T的变量(“x可以分配给T”):
> * x的类型V和T具有相同的底层类型,并且V或T中至少有一个不是定义类型。
> * ...

我在测试这个时遇到了问题。 “assignability”是否允许类型转换(我猜是的)?
如果是这样,为什么
https://play.golang.org/p/Y-U5ruLH_bd
能够编译,即使type_x和type_y都是定义类型?

如果assignability的概念不允许类型转换,为什么
https://play.golang.org/p/dHDq9nnWSMC
不能编译,即使int和type_x具有相同的底层类型?

英文:

https://golang.org/ref/spec#Assignability says:

> A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:
> * x's type V and T have identical underlying types and at least one of V
> or T is not a defined type.
> * ...

I have trouble testing this. Does "assignability" allow for casting (I guess yes)?
If so, why does
https://play.golang.org/p/Y-U5ruLH_bd
compile, even though both type_x and type_y are defined types?

If concept of assignability does not allow casting, why does
https://play.golang.org/p/dHDq9nnWSMC
NOT compile, even though int and type_x have same underlying types?

答案1

得分: 2

我相信你正在寻找的是 https://golang.org/ref/spec#Conversions

简而言之,你不是将类型为 type_y 的值直接赋给类型为 type_x 的变量,而是在赋值之前将该值转换为 type_x 类型。转换的限制要宽松得多。

直接将 y 的值赋给 x 是不被编译器允许的,原因就是你提供的链接中所述。

英文:

I believe https://golang.org/ref/spec#Conversions was what you were looking for.

In short, you are not assigning a value of type type_y to a variable of type type_x, but rather converting that value to one of type type_x before assigning it. The restrictions on conversions are a lot less tight.

Directly assigning the value of y to x will not be allowed by the compiler, for the reasons you linked to.

huangapple
  • 本文由 发表于 2021年9月7日 02:42:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/69079043.html
匿名

发表评论

匿名网友

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

确定