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.
Define a type alias for string
i.e., Suit
. The Suit
is a type whose underlying type is a string.
Now, create some constants of type Suit. In the following ode, Spade
, Diamond
, Club
, Heart
are of type Suit. Now the function in which you want the parameter to be restricted to some input (which is not possible); but what you can do it to restrict it accept the Suit
type only, and pass any of the const
variable created.
// Define new type alias for string
type Suit string
const (
Spade Suit = "Spade"
Diamond Suit = "Diamond"
Club Suit = "Club"
Heart Suit = "Heart"
)
// function f only accepts parameter of type "Suit"
func f(s Suit) {
fmt.Println(s)
}
func main() {
// Call the function f with Spade
f(Spade)
}