各种形式的整数切片转换

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

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

变量 isints 具有不同的类型,然而编译器却可以编译通过这一行代码:

is = ints

类似地,变量 ismyInts 也具有不同的类型,但在这种情况下,以下代码行无法编译通过,因为变量的类型不同:

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

一个有效赋值的条件之一是:

> VT 具有相同的底层类型,但它们不是类型参数,并且至少有一个 V 或 T 不是命名类型


is 变量的类型 []int 是一个未命名类型,它的底层类型与自身相同,即 []intints 变量的类型 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.

huangapple
  • 本文由 发表于 2022年9月17日 16:46:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/73753440.html
匿名

发表评论

匿名网友

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

确定