You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
706 B
45 lines
706 B
package misc
|
|
|
|
// Result 使用泛型模仿 Rust 实现一个简单的 Result 类型
|
|
// https://juejin.cn/post/7161342717190996005
|
|
type Result[T any] struct {
|
|
value T
|
|
err error
|
|
}
|
|
|
|
func (r *Result[T]) Ok() bool {
|
|
return r.err != nil
|
|
}
|
|
|
|
func (r *Result[T]) Err() error {
|
|
return r.err
|
|
}
|
|
|
|
func (r *Result[T]) Unwrap() T {
|
|
if r.err != nil {
|
|
panic(r.err)
|
|
}
|
|
return r.value
|
|
}
|
|
|
|
func (r *Result[T]) Expect(err error) T {
|
|
if r.err != nil {
|
|
panic(err)
|
|
}
|
|
return r.value
|
|
}
|
|
|
|
func NewResult[T any](v T, err error) *Result[T] {
|
|
return &Result[T]{
|
|
value: v,
|
|
err: err,
|
|
}
|
|
}
|
|
|
|
func Match[T any](r *Result[T], okF func(T), errF func(error)) {
|
|
if r.err != nil {
|
|
errF(r.err)
|
|
} else {
|
|
okF(r.value)
|
|
}
|
|
}
|
|
|