While reading go specification "Assignability" section, I tried to execute a couple of examples to get a better understanding of the topic, and now I can't get what am I doing wrong in my code.
According to the specification,
One of the cases when a value x is assignable to a variable of type T is as follows:
x's type V and T have identical underlying types and at least one of V or T is not a defined type.
Defined type specification states that
Type definition creates a new, distinct type with the same underlying type and operations as the given type, and binds an identifier to it.
But when I try to run following code, the build fails:
func main() {
    type Defined int32
    var d Defined
    var i int32
    d = i
}
The output is:
cannot use i (type int32) as type Defined in assignment
Meanwhile, the similar example with composite literal works fine:
func main() {
    type MyMap map[string]int
    var x MyMap 
    var y map[string]int
    x = y
}
playground
The <- operator represents the idea of passing a value from a channel to a reference. If you think of the channel as a queue using an assignment operator = would assign the reference to the queue to the target variable.
String literals A string literal represents a string constant obtained from concatenating a sequence of characters. There are two forms: raw string literals and interpreted string literals. Raw string literals are character sequences between back quotes, as in `foo` .
A quick way to check the type of a value in Go is by using the %T verb in conjunction with fmt. Printf . This works well if you want to print the type to the console for debugging purposes.
Also from the spec:
https://golang.org/ref/spec#Numeric_types
To avoid portability issues all numeric types are defined types and thus distinct
Since type Defined int32 defines a new type, d and i don't have identical types; hence, the first clause x's type is identical to T from the assignability spec isn't applicable.  The second clause x's type V and T have identical underlying types and at least one of V or T is not a defined type is not applicable as the types of both i and d are defined types.  As the remaining clauses from the assignability spec do not apply in this situation, the assignment fails.  Changing type Defined int32 to type Defined = int32 (which aliases a type) fixes the error.
x = y due to the T is an interface type and x implements T clause from the assignability spec is applicable.
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