映射键的惯用else if链

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

Idiomatic else if chain for a map key

问题

我有一个相当长的else if链,用于在映射中查找键并设置特定的值(如果找到)。我选择用最少的代码来实现,代码如下(m是一个map[string]interface{}):

var ok bool
var s interface{}
if s, ok = m["key1"]; ok {
} else if s, ok = m["key2"]; ok {
           ....
} else if s, ok = m["keyN"]; ok {
} else {
   return RuhRohError
}
g.Id = s.(string)

这种方式感觉有点笨拙,我在条件语句中使用了这么多的else if来设置一个变量。有没有一种惯用的方法来做到这一点?我觉得这种方式不会立即清楚我想要做什么。

英文:

I have a fairly long else if chain looking for keys in a map and setting a specific value if found. The way I chose to do it with the least amount of code was this (m is a map[string]interface{})

var ok bool
var s interface{}
if s, ok = m["key1"]; ok {
} else if s, ok = m["key2"]; ok {
           ....
} else if s, ok = m["keyN"]; ok {
} else {
   return RuhRohError
}
g.Id = s.(string)

This feels kinda clunky, I am doing all of these else if's to set a variable in the condition. Is there an idiomatic way to do this? I think this way doesn't make it immediately obvious what I am trying to do.

答案1

得分: 2

例如,

package main

import "fmt"

func findValue(m map[string]interface{}, keys []string) (interface{}, bool) {
    for _, key := range keys {
        if value, ok := m[key]; ok {
            return value, true
        }
    }
    return nil, false
}

func main() {
    m := map[string]interface{}{"keyn": "valuen"}
    keys := []string{"key1", "key2", "keyn"}
    s, found := findValue(m, keys)
    if !found {
        return
    }
    id := s.(string)
    fmt.Println(id)
}

输出:

valuen
英文:

For example,

package main

import "fmt"

func findValue(m map[string]interface{}, keys []string) (interface{}, bool) {
	for _, key := range keys {
		if value, ok := m[key]; ok {
			return value, true
		}
	}
	return nil, false
}

func main() {
	m := map[string]interface{}{"keyn": "valuen"}
	keys := []string{"key1", "key2", "keyn"}
	s, found := findValue(m, keys)
	if !found {
		return
	}
	id := s.(string)
	fmt.Println(id)
}

Output:

valuen

答案2

得分: 1

实际上,我认为你提供的代码非常容易阅读和理解。它有点啰嗦,但没有什么神奇的东西;)。所以如果只有一个地方需要编写这段代码,我会保持原样。如果你需要多次编写它,我会考虑编写另一个评论中提到的findValue函数。

英文:

Actually I think the code you provided is very easy to read and understand. It is a bit verbose but there is no magic ;). So if there is only one place where you have to write this code I would leave it as it is. If you need to write it a few times I would consider writing findValue function mentioned in another comment.

huangapple
  • 本文由 发表于 2015年5月27日 09:20:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/30471586.html
匿名

发表评论

匿名网友

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

确定