Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignability question in golang specification

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

like image 408
Nick B Avatar asked Dec 28 '19 00:12

Nick B


People also ask

What does <- mean in Golang?

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.

What is string literal in Go programming?

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` .

How a variable type is checked at runtime in Go language?

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.


2 Answers

Also from the spec:

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

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

like image 87
Burak Serdar Avatar answered Oct 08 '22 16:10

Burak Serdar


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.

like image 44
Venkatesh-Prasad Ranganath Avatar answered Oct 08 '22 16:10

Venkatesh-Prasad Ranganath