英文:
Pop a value from a map using one lookup
问题
如何在Go中实现一个函数,使用只有一个查找操作从映射中弹出一个键?以下版本在映射上进行了两次查找:
package main
import "fmt"
func main() {
m := map[string]int{"a": 1, "b": 2}
a, ok := m["a"]
if ok {
delete(m, "a")
}
fmt.Println(a, m)
}
我检查了一下delete
是否返回被删除键的值:
package main
func main() {
m := map[string]int{"a": 1, "b": 2}
println(delete(m, "a"))
}
但这样是不起作用的:
prog.go:5: delete(m, "a") used as value
你可以尝试使用以下代码来实现只使用一个查找操作从映射中弹出一个键:
package main
import "fmt"
func popKey(m map[string]int, key string) (int, bool) {
value, ok := m[key]
if ok {
delete(m, key)
}
return value, ok
}
func main() {
m := map[string]int{"a": 1, "b": 2}
a, ok := popKey(m, "a")
fmt.Println(a, m)
}
这样,popKey
函数将从映射中弹出指定的键,并返回该键对应的值以及一个布尔值,指示键是否存在于映射中。
英文:
How to implement in Go a function that pops a key from a map using just one lookup? This version does two lookups on the map:
package main
import "fmt"
func main() {
m := map[string]int{"a":1, "b":2}
a, ok := m["a"]
if ok {
delete(m, "a")
}
fmt.Println(a, m)
}
I checked maybe delete
returns the value of deleted key:
package main
func main() {
m := map[string]int{"a":1, "b":2}
println(delete(m, "a"))
}
But this doesn't work:
prog.go:5: delete(m, "a") used as value
答案1
得分: 5
Go语言中的map类型没有Pop
函数,所以总是需要进行两个操作,即索引和delete
。
如果你担心冗长的代码和性能问题,可以使用一个小的辅助函数,这样它会被内联,使用它不会增加额外的运行时开销。
func pop(m map[string]int, key string) (int, bool) {
v, ok := m[key]
if ok {
delete(m, key)
}
return v, ok
}
英文:
Go doesn't have a Pop
function for maps, so there will always be 2 operations, a index and a delete
.
If you're worried about verbosity and performance, and small helper function like so would be inlined, so there's no extra runtime overhead to using it.
func pop(m map[string]int, key string) (int, bool) {
v, ok := m[key]
if ok {
delete(m, key)
}
return v, ok
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论