Assignability question in golang specification
Asked Answered
F

2

5

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

Folksy answered 28/12, 2019 at 0:54 Comment(0)
G
6

Also from the spec:

https://golang.org/ref/spec#Numeric_types

To avoid portability issues all numeric types are defined types and thus distinct

Group answered 28/12, 2019 at 1:19 Comment(1)
So, since both are defined types, they cannot be assigned to each other directly. You can however say d = Defined(i)Concent
S
4

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.

Synonymize answered 28/12, 2019 at 1:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.