Documentation
¶
Overview ¶
Package enum provides an enumerated type.
Example ¶
package main
import (
"fmt"
"github.com/phelmkamp/valor/enum"
"github.com/phelmkamp/valor/tuple/two"
"time"
)
const (
Clubs = "clubs"
Diamonds = "diamonds"
Hearts = "hearts"
Spades = "spades"
Apple = iota
Banana
Orange
)
var (
Suit = enum.OfString(Clubs, Diamonds, Hearts, Spades)
Fruit = enum.Of(
two.TupleOf("apple", Apple),
two.TupleOf("banana", Banana),
two.TupleOf("orange", Orange),
)
)
var Event = enum.OfText(
time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC),
time.Date(2000, time.January, 1, 0, 0, 0, 0, time.UTC),
)
func main() {
fmt.Println(Suit.Values())
fmt.Println(Suit.ValueOf("Foo"))
fmt.Println(Suit.ValueOf(Hearts))
fmt.Println(Fruit.ValueOf(Orange))
fmt.Println(Event.ValueOf(time.UnixMilli(0).UTC()))
}
Output: [clubs diamonds hearts spades] { false} {hearts true} {orange true} {1970-01-01T00:00:00Z true}
Example (Marshal) ¶
Example_marshal demonstrates that an enum.Enum can be marshaled to and unmarshaled from text (and therefore JSON).
package main
import (
"fmt"
"github.com/phelmkamp/valor/enum"
"github.com/phelmkamp/valor/tuple/two"
)
const (
Clubs = "clubs"
Diamonds = "diamonds"
Hearts = "hearts"
Spades = "spades"
Apple = iota
Banana
Orange
)
var Fruit = enum.Of(
two.TupleOf("apple", Apple),
two.TupleOf("banana", Banana),
two.TupleOf("orange", Orange),
)
func main() {
var text []byte
text, _ = Fruit.ValueOf(Apple).MarshalText()
fav := Fruit
_ = fav.UnmarshalText(text)
fmt.Println(fav)
}
Output: {apple true}
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type ComparableText ¶
type ComparableText interface {
comparable
encoding.TextMarshaler
}
ComparableText is a constraint that permits comparable types that can be marshaled to text.
type Enum ¶
type Enum[T comparable] struct { optional.Value[T] // contains filtered or unexported fields }
Enum is an enumerated type.
It wraps an optional.Value that is only ok if it's a member of the allowed values.
func Of ¶
func Of[T comparable](pairs ...two.Tuple[string, T]) Enum[T]
Of creates an Enum of the given name-value pairs.
func OfText ¶
func OfText[T ComparableText](vals ...T) Enum[T]
OfText creates an Enum of the given text values. Panics if MarshalText returns an error for one of the values.
func (Enum[T]) MarshalText ¶
MarshalText returns the name of the current member. Returns nil if e is not ok.
func (*Enum[T]) UnmarshalText ¶
UnmarshalText sets e to wrap the member with the given name. Sets e to not-ok if text is not the name of a valid member.