In the book "Go in Action", the author wrote "Values of two different types can’t be assigned to each other, even if they’re compatible".
For example, we can't assign Duration
to int64
or int64
to Duration
.
But this is not always true, the following assignment would work like the X
value is converted back to []int
automatically:
type X []int
var v []int = X([]int{1, 2, 3})
What's the difference between these two situations?
The first time a variable is assigned a value, it is said to be initialised. The = symbol is known as the assignment operator. It is also possible to declare a variable and assign it a value in the same line, so instead of int i and then i = 9 you can write int i = 9 all in one go.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
A variable is a characteristic that can be measured and that can assume different values.
Assigning values to variables is achieved by the = operator. The = operator has a variable identifier on the left and a value on the right (of any value type). Assigning is done from right to left, so a statement like var sum = 5 + 3; will assign 8 to the variable sum .
I'll refer you to the spec and excerpt the most meaningful lines here:
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
...
- x's type V and T have identical underlying types and at least one of V or T is not a named type.
In your example the underlying type is []int
for each case and []int
is not a named type but a slice. An int
would actually constitute a named type (predeclared in the universe block) and would have itself as an underlying type, but []int
is not a named type as detailed here:
Named instances of the boolean, numeric, and string types are predeclared. Composite types—array, struct, pointer, function, interface, slice, map, and channel types—may be constructed using type literals.
Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.
Therefore if you tried making type X int
you would not be able to assign it to var v int
as int
is a named type and would not satisfy the assignability criteria given in the spec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With