mandaputtra
mandaputtra

Reputation: 1070

Cannot use 1 (type int) as type *int in field value

Why does this yield error? It's the same int except the with pointer.

type Gim struct {Active: *int}
yesVar := Gim{Active: 1}
// error
// Cannot use 1 (type int) as type *int in field value

Although when I use it like this

type Gim struct {Active: *int}
active := 1 
yesVar := Gim{Active: &active}
// compiles

It compiles and doesn't yield error, any explanation why is that?

Upvotes: 3

Views: 15292

Answers (1)

saedx1
saedx1

Reputation: 1085

In the second example, you are assigning a pointer of integer (*int) to a field of the same type (*int). However, in the first one, you are assigning an int to *int. This is a mismatch and you can't do it because the two types aren't the same. int is a type that holds integer values (e.g. 0, 100, -55, ...), and *int is a type that holds addresses to int values in memory (e.g. address 0x00124215, ...). So, you can see how both don't actually represent the same type.

If you want to still do it in a single line, you would have to define a function that takes a value and returns a pointer:

func GetIntPointer(value int) *int {
    return &value
}

yesVar := Gim{Active: GetIntPointer(1)}

Upvotes: 3

Related Questions