Skip to content

Instantly share code, notes, and snippets.

@chenlujjj
Created March 31, 2021 15:21
Show Gist options
  • Save chenlujjj/361c7ce3c2a222b0fa270049734e3d5d to your computer and use it in GitHub Desktop.
Save chenlujjj/361c7ce3c2a222b0fa270049734e3d5d to your computer and use it in GitHub Desktop.
枚举类型的惯用写法(包括和字符串的相互转换)
package main
import (
"errors"
"fmt"
"strings"
)
var ErrInvalidFruit = errors.New("invalid fruit")
type Fruit int
const (
InvalidFruit Fruit = iota - 1
Apple
Orange
Banana
Pear
Grape
)
var fruitNames = [...]string{
Apple: "apple",
Orange: "orange",
Banana: "banana",
Pear: "pear",
Grape: "grape",
}
var fruitStrings = map[string]Fruit{
"apple": Apple,
"orange": Orange,
"banana": Banana,
"pear": Pear,
"grape": Grape,
}
func (f Fruit) String() string {
return fruitNames[f]
}
func ParseFruit(s string) (Fruit, error) {
f, ok := fruitStrings[strings.ToLower(s)]
if !ok {
return InvalidFruit, ErrInvalidFruit
}
return f, nil
}
func main() {
f, _ := ParseFruit("Apple")
fmt.Println(f)
// output: apple
fmt.Println(Orange)
// output: orange
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment