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.
CodePudding user response:
One of the conditions for a valid assignment is the following:
V
andT
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.