英文:
Check if value exists in enum
问题
我在我的应用程序中创建了以下严格的代码:
type Datatype int8
const (
user Datatype = iota
address
test
)
var datatypes = [...]string{"User", "Address", "Test"}
func (datatype Datatype) String() string {
return datatypes[datatype]
}
我想要能够使用命令行标志验证传递的值是否符合此枚举类型。
我记得我曾经看到过类似dtype == Datatype
这样的用法,但显然我弄错了。
如果这不可能的话,我可以将这些值放入一个数组中。然而,我觉得枚举的方法更加优雅。
英文:
I have created a strict like the following in my app:
<pre>type Datatype int8
const (
user Datatype = iota
address
test
)
var datatypes = [...]string{"User", "Address", "Test"}
func (datatype Datatype) String() string {
return datatypes[datatype]
}</pre>
I would like to be able to validate a value passed via a command-line flag against this enum.
I thought I had seen something like dtype == Datatype
being used, but I am apparently sorely mistaken.
If this is not possible I can go the route of putting these values in an array. However, I feel the enum approach is more elegant.
答案1
得分: 5
从你的代码示例中看,你想要判断一个 map(而不是一个结构体)是否包含特定的键。
如果是这样,答案在这里
> 一个双值赋值用于测试键的存在性:
>
> i, ok := m["route"]
> 在这个语句中,第一个值(i)被赋予存储在键"route"下的值。如果该键不存在,i将是该值类型的零值(0)。第二个值(ok)是一个布尔值,如果键存在于 map 中则为 true,否则为 false。
>
> 如果只想测试键而不检索值,请在第一个值的位置使用下划线:
>
> _, ok := m["route"]
英文:
From your code sample it looks like you are trying to see if a map (rather than a struct) contains a particular key.
If so, the answer is here
> A two-value assignment tests for the existence of a key:
>
> i, ok := m["route"]
> In this statement, the first value (i) is assigned
> the value stored under the key "route". If that key doesn't exist, i
> is the value type's zero value (0). The second value (ok) is a bool
> that is true if the key exists in the map, and false if not.
>
> To test for a key without retrieving the value, use an underscore in
> place of the first value:
>
> _, ok := m["route"]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论