Created
March 31, 2021 15:21
-
-
Save chenlujjj/361c7ce3c2a222b0fa270049734e3d5d to your computer and use it in GitHub Desktop.
枚举类型的惯用写法(包括和字符串的相互转换)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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