Closed xujihui1985 closed 1 year ago
Hi @xujihui1985
the match function for Either is named Fold.
You could e.g. write your example like so (avoiding explicit branching and using point-free style:
import (
"fmt"
E "github.com/IBM/fp-go/either"
"github.com/IBM/fp-go/errors"
F "github.com/IBM/fp-go/function"
O "github.com/IBM/fp-go/option"
S "github.com/IBM/fp-go/string"
)
type Thing struct {
Name string
}
func (t Thing) GetName() string {
return t.Name
}
var (
// func(Thing) Either[error, string]
getName = F.Flow2(
Thing.GetName,
E.FromPredicate(S.IsNonEmpty, errors.OnSome[string]("value [%s] is empty")),
)
// func(option.Option[Thing]) Either[error, string]
GetName = F.Flow2(
E.FromOption[Thing](errors.OnNone("value is none")),
E.Chain(getName),
)
)
func ExampleEither_match() {
oThing := O.Of(Thing{"Carsten"})
res := F.Pipe2(
oThing,
GetName,
E.Fold(S.Format[error]("failed with error %v"), S.Format[string]("get value %s")),
)
fmt.Println(res)
// Output:
// get value Carsten
}
Judging based on your example it looked like NewThing("hello")
returned an Option[Thing]
.
In your example you then lift that Option
into an Either
.
In case the underlying usecase is to select an optional Name
attribute from an optional Thing
you could also consider to stay with the Option
type all along and just use O.Chain
.
thank you for show me the idiomatic way to doing that. That's helpful.
I wander how can I handle the either type, say in the main function I want to print the error and exit if val is left or log the value if it is right, can we introduce a Match function in Either ? Or there is better way to do that?