这里需要用到enum库
go get -u github.com/younamebert/enum
-
定义一个枚举类型
package main
import (
"fmt"
"github.com/younamebert/enum"
)
var sex enum.Enum
func main() {
//0,1,2
sex = enum.NewEnum("man", "woman", "secrecy")
}
-
操作枚举enum
package main
import (
"fmt"
"github.com/younamebert/enum"
)
var sex enum.Enum
func main() {
//0,1,2
sex = enum.NewEnum("man", "woman", "secrecy")
fmt.Println(sex.IsEnum("man")) // true
fmt.Println(sex.IsEnums("woman", "woman")) // true
fmt.Println(sex.IsEnum("abc")) // false
fmt.Println(sex.IsEnums("man", "abc")) // false
}
查看枚举值
package main
import (
"fmt"
"github.com/younamebert/enum"
)
var sex enum.Enum
func main() {
//0,1,2
sex = enum.NewEnum("man", "woman", "secrecy")
value, err := sex.Enum("man")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(value) //0
values, err := sex.Enums("man", "secrecy")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(values) //[0 2]
_, err = sex.Enum("abc")
if err != nil {
fmt.Println(err) //does not exist in the enum
return
}
}
修改自定义枚举值
package main
import (
"fmt"
"github.com/younamebert/enum"
)
var sex enum.Enum
func main() {
//0,1,2
sex = enum.NewEnum("man", "woman", "secrecy")
if err := sex.SetEnum("man", 4); err != nil {
fmt.Println(err)
return
}
value, err := sex.Enum("man")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(value) //4
}
添加和移除枚举值
package main
import (
"fmt"
"github.com/younamebert/enum"
)
var sex enum.Enum
func main() {
//0,1,2
sex = enum.NewEnum("man", "woman", "secrecy")
//append
if err := sex.AppendEnum("abc"); err != nil {
fmt.Println(err)
return
}
value, err := sex.Enum("abc")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(value) //3
//remove
if err := sex.RemoveEnum("abc"); err != nil {
fmt.Println(err)
return
}
value, err = sex.Enum("abc")
if err != nil {
fmt.Println(err) // does not exist in the enum
return
}
fmt.Println(value)
}
网友评论