github.com/go-playground/pkg/v5@v5.29.1/values/result/result.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package resultext 5 6 // Result represents the result of an operation that is successful or not. 7 type Result[T, E any] struct { 8 ok T 9 err E 10 isOk bool 11 } 12 13 // Ok returns a Result that contains the given values. 14 func Ok[T, E any](value T) Result[T, E] { 15 return Result[T, E]{ok: value, isOk: true} 16 } 17 18 // Err returns a Result that contains the given error. 19 func Err[T, E any](err E) Result[T, E] { 20 return Result[T, E]{err: err} 21 } 22 23 // IsOk returns true if the result is successful with no error. 24 func (r Result[T, E]) IsOk() bool { 25 return r.isOk 26 } 27 28 // IsErr returns true if the result is not successful and has an error. 29 func (r Result[T, E]) IsErr() bool { 30 return !r.isOk 31 } 32 33 // Unwrap returns the values of the result. It panics if there is no result due to not checking for errors. 34 func (r Result[T, E]) Unwrap() T { 35 if r.isOk { 36 return r.ok 37 } 38 panic("Result.Unwrap(): result is Err") 39 } 40 41 // UnwrapOr returns the contained Ok value or a provided default. 42 // 43 // Arguments passed to UnwrapOr are eagerly evaluated; if you are passing the result of a function call, 44 // look to use `UnwrapOrElse`, which can be lazily evaluated. 45 func (r Result[T, E]) UnwrapOr(value T) T { 46 if r.isOk { 47 return r.ok 48 } 49 return value 50 } 51 52 // UnwrapOrElse returns the contained Ok value or computes it from a provided function. 53 func (r Result[T, E]) UnwrapOrElse(fn func() T) T { 54 if r.isOk { 55 return r.ok 56 } 57 return fn() 58 } 59 60 // UnwrapOrDefault returns the contained Ok value or the default value of the type T. 61 func (r Result[T, E]) UnwrapOrDefault() T { 62 return r.ok 63 } 64 65 // And calls the provided function with the contained value if the result is Ok, returns the Result value otherwise. 66 func (r Result[T, E]) And(fn func(T) T) Result[T, E] { 67 if r.isOk { 68 r.ok = fn(r.ok) 69 } 70 return r 71 } 72 73 // AndThen calls the provided function with the contained value if the result is Ok, returns the Result value otherwise. 74 // 75 // This differs from `And` in that the provided function returns a Result[T, E] allowing changing of the Option value 76 // itself. 77 func (r Result[T, E]) AndThen(fn func(T) Result[T, E]) Result[T, E] { 78 if r.isOk { 79 return fn(r.ok) 80 } 81 return r 82 } 83 84 // Err returns the error of the result. To be used after calling IsOK() 85 func (r Result[T, E]) Err() E { 86 return r.err 87 }