Go中的自定义字符串类型
如何在 Go 中创建仅限于特定字符串值列表的自定义类型?例如
type Suit = "Spade" | "Diamond" | "Club" | "Heart"
回答
Go does not have Algebraic data types (ADT). What you want is "sum" type in ADT. For example there are enums in Swift and Rust to support them.
Go does not have generics(yet); there is no Option, Result type as well.
While what you want to do can be achieved using different ways in Go, I like using const instead of empty interface or type check or reflection. I think const would be more faster and readable. Here is how I will go. You can return the string from method instead of printing if that is what you want.
package main
import "fmt"
type Suit int
const (
Spade Suit = iota + 1
Diamond
Club
Heart
)
type Card struct {
suit Suit
no int
}
func (c *Card) PrintSuit() {
switch c.suit {
case Spade:
fmt.Println("Its a Spade")
case Diamond:
fmt.Println("Its a Diamond")
case Club:
fmt.Println("Its a Club")
case Heart:
fmt.Println("Its a Heart")
default:
fmt.Println("Unknown!")
}
}
func main() {
c := Card{suit: Diamond}
c.PrintSuit()
}
You can accept external func in methods like PrintSuit if the processing logic is external.