dongtangxi1584
dongtangxi1584
2014-09-11 18:39
浏览 4
已采纳

结构类型不可变

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxue4395
    douxue4395 2014-09-11 18:45
    已采纳

    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 )

    点赞 评论
  • duancheng3042
    duancheng3042 2014-09-11 18:47

    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.

    点赞 评论

相关推荐