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

Nick B
  • 141
  • 1
  • 7

2 Answers2

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

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • So, since both are defined types, they cannot be assigned to each other directly. You can however say `d = Defined(i)` – erik258 Dec 28 '19 at 01:29
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.