map - 尝试在 Go 中实现 map 合并功能但失败

标签 map merge go

问题的最简单再现:

package main

import "fmt"

type stringMap map[int]string

func (s *stringMap) Merge(m stringMap) {
    for key, value := range m {
        s[key] = value
    }
}

func main() {
    myMap := stringMap{1: "a", 2: "b"}
    myMap.Merge(stringMap{3: "c"})
    fmt.Println(myMap)
}

为什么我不能使用 key 变量作为 mymap stringMap 上的键?

Playground :http://play.golang.org/p/mSprMXq5QF

最佳答案

您不能在指向 map 的指针上使用索引(访问 map )。

您只需进行以下更改(请注意已删除的 *):

func (s stringMap) Merge(m stringMap) { ... }

关于map - 尝试在 Go 中实现 map 合并功能但失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27312205/

相关文章:

map - 在 golang 中分配给 map

c++ - 按索引访问 map 值

python - 如何在 pandas 中添加 concat 指示符列?

git - git merge another-branch 和 git pull remote another-branch 的区别

multithreading - 如何安排运行的非阻塞函数

像 C++ map 这样的 Java 容器

c++ - 在 C++ 中获取多重映射的值

git - 强制提交在提交时有额外的 parent

go - 回声服务器扭曲图像响应主体

go - 找不到包 "testing/internal/testdeps"