Created
April 22, 2022 10:49
-
-
Save wirekang/372054026f5f7db887d55485b8ee4ca2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 errutil | |
import ( | |
"context" | |
"github.com/samber/lo" | |
) | |
func Delay[T any](target *error) func(v T, err error) T { | |
a := func(v T, err error) T { | |
if *target == nil && err != nil { | |
*target = err | |
} | |
return v | |
} | |
return a | |
} | |
type Person struct { | |
name string | |
age int | |
email string | |
} | |
func getName(context.Context) (string, error) { return "", nil } | |
func getEmail(context.Context) (string, error) { return "", nil } | |
func getAge(context.Context) (int, error) { return 0, nil } | |
func SamplePureGo(ctx context.Context) (person *Person, err error) { | |
name, err := getName(ctx) | |
if err != nil { | |
return | |
} | |
email, err := getEmail(ctx) | |
if err != nil { | |
return | |
} | |
age, err := getAge(ctx) | |
if err != nil { | |
return | |
} | |
person = &Person{ | |
name: name, | |
age: age, | |
email: email, | |
} | |
return | |
} | |
func SampleDelay(ctx context.Context) (person *Person, err error) { | |
dInt := Delay[int](&err) | |
dString := Delay[string](&err) | |
person = &Person{ | |
name: dString(getName(ctx)), | |
age: dInt(getAge(ctx)), | |
email: dString(getEmail(ctx)), | |
} | |
return | |
} | |
func SampleLo(ctx context.Context) (person *Person, err error) { | |
reason, ok := lo.TryWithErrorValue(func() error { | |
person = &Person{ | |
name: lo.Must(getName(ctx)), | |
age: lo.Must(getAge(ctx)), | |
email: lo.Must(getEmail(ctx)), | |
} | |
return nil | |
}) | |
if ok { | |
return | |
} | |
err = reason.(error) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment