Created
May 23, 2022 11:44
-
-
Save nikomartn/ffc932e38b96d576d381e5625d8c4aff to your computer and use it in GitHub Desktop.
Go type enums
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 "fmt" | |
type AnEnum interface { | |
IAmAnEnum() | |
} | |
type Text struct { | |
text string | |
} | |
func (Text) IAmAnEnum() {} | |
type Number struct { | |
number int | |
} | |
func (Number) IAmAnEnum() {} | |
type Error struct{} | |
func (Error) IAmAnEnum() {} | |
func GetData(enum AnEnum) { | |
switch enum.(type) { | |
case Text: | |
fmt.Println("It was text: ", enum.(Text).text) | |
case Number: | |
fmt.Println("It was number: ", enum.(Number).number) | |
case Error: | |
fmt.Println("It was an error") | |
} | |
} | |
func main() { | |
var anEnum AnEnum = Text{"Hello"} | |
GetData(anEnum) | |
var anEnum2 AnEnum = Number{27} | |
GetData(anEnum2) | |
var anEnum3 AnEnum = Error{} | |
GetData(anEnum3) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment