How can I create a custom type in Go that is restricted to a certain list of string values? e.g.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With