英文:
Convertion of various form of int slices
问题
假设我有以下类型:
type MyInt int
type Ints []int
type MyInts []MyInt
使用这些类型,我定义了一些变量:
var is []int
var ints Ints
var myInts MyInts
变量 is 和 ints 具有不同的类型,然而编译器却可以编译通过这一行代码:
is = ints
类似地,变量 is 和 myInts 也具有不同的类型,但在这种情况下,以下代码行无法编译通过,因为变量的类型不同:
is = myInts
那么,为什么在第一种情况下,类型的差异不会阻止编译,而在第二种情况下会阻止编译呢?
这里有一个简单的示例代码,可以重现这种情况。
英文:
Let's assume I have these types
type MyInt int
type Ints []int
type MyInts []MyInt
Using these types I define some variables
var is []int
var ints Ints
var myInts MyInts
The variables is and ints have different type, however the compiler happily compiles this line
is = ints
Similarly is and myInts have different types, but in this case the following line is not compiled because the types of the variables are different
is = myInts
So, why in the first case the difference of types does not stop comlilation, while in the second case it does stop it?
Here a simple playground that reproduces the case.
答案1
得分: 3
一个有效赋值的条件之一是:
> V 和 T 具有相同的底层类型,但它们不是类型参数,并且至少有一个 V 或 T 不是命名类型。
is 变量的类型 []int 是一个未命名类型,它的底层类型与自身相同,即 []int。ints 变量的类型 Ints 是一个命名类型,它的底层类型是 []int。
因此,赋值 is = ints 是有效的。
myInts 变量的类型 MyInts 是一个命名类型,它的底层类型是 []MyInt。类型 []MyInt 与 []int 不相同。
因此,赋值 is = myInts 是无效的。
英文:
One of the conditions for a valid assignment is the following:
> V and T have identical underlying types but are not type parameters and at least one of V or T is not a named type.
The is variable's type []int is an unnamed type, it's underlying type is identical to itself, i.e. []int. The type of ints variable, i.e. Ints, is a named type, it's underlying type []int.
Hence the assignment is = ints is valid.
The myInts variable's type MyInts is a named type, it's underlying type is []MyInt. Type []MyInt is not identical to []int.
Hence the assignment is = myInts is not valid.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论