Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom string types in Go [duplicate]

Tags:

go

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"
like image 587
Jimmy Avatar asked Oct 20 '25 14:10

Jimmy


1 Answers

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.

like image 148
Abhijit-K Avatar answered Oct 23 '25 07:10

Abhijit-K