diff --git a/utils/super/match.go b/utils/super/match.go new file mode 100644 index 0000000..4c83a8b --- /dev/null +++ b/utils/super/match.go @@ -0,0 +1,34 @@ +package super + +import "reflect" + +// Matcher 匹配器 +type Matcher[Value, Result any] struct { + value Value + r Result + d bool +} + +// Match 匹配 +func Match[Value, Result any](value Value) *Matcher[Value, Result] { + return &Matcher[Value, Result]{ + value: value, + } +} + +// Case 匹配 +func (slf *Matcher[Value, Result]) Case(value Value, result Result) *Matcher[Value, Result] { + if !slf.d && reflect.DeepEqual(slf.value, value) { + slf.r = result + slf.d = true + } + return slf +} + +// Default 默认 +func (slf *Matcher[Value, Result]) Default(value Result) Result { + if slf.d { + return slf.r + } + return value +} diff --git a/utils/super/match_test.go b/utils/super/match_test.go new file mode 100644 index 0000000..3f094c0 --- /dev/null +++ b/utils/super/match_test.go @@ -0,0 +1,24 @@ +package super_test + +import ( + "github.com/kercylan98/minotaur/utils/super" + . "github.com/smartystreets/goconvey/convey" + "testing" +) + +func TestMatch(t *testing.T) { + Convey("TestMatch", t, func() { + So(super.Match[int, string](1). + Case(1, "a"). + Case(2, "b"). + Default("c"), ShouldEqual, "a") + So(super.Match[int, string](2). + Case(1, "a"). + Case(2, "b"). + Default("c"), ShouldEqual, "b") + So(super.Match[int, string](3). + Case(1, "a"). + Case(2, "b"). + Default("c"), ShouldEqual, "c") + }) +}