feat: super 包支持 match 控制函数
This commit is contained in:
parent
c1e3c65c1c
commit
25ed712fc9
|
@ -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
|
||||
}
|
|
@ -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")
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue