Go中Map原地修改value

2017-07-11  本文已影响0人  浑浑噩噩_邋邋遢遢
首先记住一句话,等号两边类型匹配

在Go语言中,Map中的值是不可以原地修改的,如:

package main

type Student struct {
    Name string
    Id int
}

func main() {
    s := make(map[string]Student)
    s["chenchao"] = Student{
        Name:"chenchao",
        Id:111,
    }
    s["chenchao"].Id = 222

}

上面的代码会编译失败,因为在go中 map中的赋值属于值copy,就是在赋值的时候是把Student的完全复制了一份,复制给了map。而在go语言中,是不允许将其修改的。
但是如果map的value为int,是可以修改的,因为修改map中的int属于赋值的操作。

package main

type Student struct {
    Name string
    Id int
}

func main() {
    s1 := make(map[string]int)
    s1["chenchao"] = 2
    s1["chenchao"] = 3
}

那么,如何在go语言中原地修改map中的value呢? 答案是:传指针!

package main

import "fmt"

type Student struct {
    Name string
    Id int
}

func main() {
    s := make(map[string]*Student)
    s["chenchao"] = &Student{
        Name:"chenchao",
        Id:111,
    }
    s["chenchao"].Id = 222
    fmt.Println(s)
}

在结构体比较大的时候,用指针效率会更好,因为不需要值copy
当然,如果map中的value为 *int指针类型,那么在赋值时不可以用&123,因为int为常亮,不占内存,没有内存地址

package main

import "fmt"

type Student struct {
    Name string
    Id int
}

func main() {
    s2 := make(map[string]*int)
    n := 1
    s2["chenchao"] = &n
    fmt.Println(s2)
}
上一篇下一篇

猜你喜欢

热点阅读