尝试在Go中实现地图合并函数,但失败了。

huangapple go评论106阅读模式
英文:

Trying to implement a map merge function in Go but failing

问题

问题的最简单复现:

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

英文:

Most simple reproduction of the issue:

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)
}

Why I can't use key variable as a key on mymap stringMap?

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

答案1

得分: 3

你不能在指向地图的指针上使用索引(访问地图)。

你只需要进行以下更改(注意删除的 *):

func (s stringMap) Merge(m stringMap) { ... }
英文:

You can't using indexing (accessing the map) on a pointer to a map.

You just have to make the following change (pay noticed to the removed *):

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

答案2

得分: 2

你可以将函数接收器更改为普通接收器(正如其他人建议的那样),或者在函数内部对其进行解引用((*s)[key] = value)。

英文:

You could either change the function receiver to a normal receiver (as others have suggested), or dereference it inside the function ((*s)[key] = value)

答案3

得分: 1

你的Merge方法的接收者是一个指向映射的指针,而映射不支持[]索引语法。如果你将接收者改为(s stringMap),一切都应该按照你的预期工作。

英文:

The receiver for your Merge method is a pointer to a map, which doesn't support the [] indexing syntax. If you change the receiver to (s stringMap), everything should work as you'd expect.

huangapple
  • 本文由 发表于 2014年12月5日 17:02:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/27312205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定