softshipper
softshipper

Reputation: 34071

Struct type immtable

I wrote a sample application about assign value to variable. Look at the following code snippet:

package main

import (
    "fmt"
)

func main() {

    cp := 344
    fmt.Println(cp)
    cp = 566565
    fmt.Println(cp)

    res := []struct {
        Email     string `json:"n.email"`
        Activated bool   `json:"n.activated"`
    }{}

    fmt.Println(res)

    res = []struct {
        Email string `json:"n.email"`
    }{}

    fmt.Println(res)
}

First cp variable, I assign value then after do it again and it works. At the end cp carry the value 566565. For me is int mutable.

The second code does not work, reassign new struct to res, I got compiler error.

./double_assignment.go:23: cannot use []struct { Email string } literal (type []struct { Email string }) as type []struct { Email string; Activated bool } in assignment

Is struct immutable?

Upvotes: 0

Views: 84

Answers (2)

andlabs
andlabs

Reputation: 11588

No, your types are incompatible. The type of res is

[]struct {
    Email     string
    Activated bool
}

but you are trying to give it a

[]struct {
    Email string
    // notice no Activated!
}

The element type of a slice is part of the type; you can't mix and match like this, even if some fields seem to be shared.

Upvotes: 2

VonC
VonC

Reputation: 1323953

The first short variable declaration res := did set a certain type ([]struct { Email string; Activated bool}).

If you want to assign a different type (here, a different struct literal []struct { Email string }), you need a different variable.

res2 = []struct {
        Email string `json:"n.email"`
}{}

fmt.Println(res2)

(as in play.golang.org )

Upvotes: 2

Related Questions