英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论