漫谈 Golang 之 map

  1. map 参数传递
  2. 无法对 map value 取地址

map 参数传递

当 map 作为参数被传递时,实际上传递的 map 的指针信息,传递后的修改会同步到函数外。

可以看到 m 被传递到了 onMap 函数中,但是最后在函数外的 m 也是被修改了的。

package main
import "fmt"
func main() {
    m := map[int]int{}
    opMap(m)
    printMap(m)
}
func opMap(m map[int]int) {
    for i := 0; i < 10; i++ {
        m[i] = i
        printMap(m)
    }
}
func printMap(m map[int]int) {
    fmt.Printf("len: %v, map: %v\n", len(m), m)
}
// Output:
// len: 1, map: map[0:0]
// len: 2, map: map[0:0 1:1]
// len: 3, map: map[0:0 1:1 2:2]
// len: 4, map: map[0:0 1:1 2:2 3:3]
// len: 5, map: map[0:0 1:1 2:2 3:3 4:4]
// len: 6, map: map[0:0 1:1 2:2 3:3 4:4 5:5]
// len: 7, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6]
// len: 8, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7]
// len: 9, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8]
// len: 10, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8 9:9]
// len: 10, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8 9:9]

无法对 map value 取地址

如下的代码中,尝试获取 map value 的地址,会在编译时显示失败。

Why Go forbid taking the address of map member

package main
import "fmt"
func main() {
    m := map[int]int{}
    address := &m[0] // invalid operation: cannot take address of m[0] (map index expression of type int)
    fmt.Println(address)
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 nickchenyx@gmail.com

Title:漫谈 Golang 之 map

Count:386

Author:nickChen

Created At:2022-07-23, 20:59:01

Updated At:2023-05-08, 23:27:10

Url:http://nickchenyx.github.io/2022/07/23/golang-map-dive-into/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.