从映射中使用一次查找弹出一个值

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

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
}

huangapple
  • 本文由 发表于 2014年7月1日 01:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/24496074.html
匿名

发表评论

匿名网友

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

确定