github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/result/result.go (about)

     1  package result
     2  
     3  type Result struct {
     4  	ok  interface{}
     5  	err error
     6  }
     7  
     8  func Ok(v interface{}) Result {
     9  	return Result{ok: v}
    10  }
    11  
    12  func Err(err error) Result {
    13  	return Result{err: err}
    14  }
    15  
    16  func (r Result) IsOk() bool {
    17  	if r.err != nil {
    18  		return false
    19  	}
    20  	return true
    21  }
    22  
    23  func (r Result) IsErr() bool { return !r.IsOk() }
    24  
    25  func (r Result) Map(fn func(interface{}) interface{}) Result {
    26  	if r.IsOk() {
    27  		return Result{ok: fn(r.ok)}
    28  	}
    29  	return Result{err: r.err}
    30  }
    31  
    32  func (r Result) MapErr(fn func(err error) error) Result {
    33  	if r.IsOk() {
    34  		return Result{ok: r.ok}
    35  	}
    36  	return Result{err: fn(r.err)}
    37  }
    38  
    39  func (r Result) And(res Result) Result {
    40  	if r.IsOk() {
    41  		return res
    42  	}
    43  	return Result{err: r.err}
    44  }
    45  
    46  func (r Result) AndThen(fn func(interface{}) Result) Result {
    47  	if r.IsOk() {
    48  		return fn(r.ok)
    49  	}
    50  	return Result{err: r.err}
    51  }
    52  
    53  func (r Result) Or(res Result) Result {
    54  	if r.IsOk() {
    55  		return Result{ok: r.ok}
    56  	}
    57  	return res
    58  }
    59  
    60  func (r Result) OrElse(fn func(err error) Result) Result {
    61  	if r.IsOk() {
    62  		return Result{ok: r.ok}
    63  	}
    64  	return fn(r.err)
    65  }
    66  
    67  func (r Result) Unwrap() interface{} {
    68  	if r.IsOk() {
    69  		return r.ok
    70  	}
    71  	panic("err: try unwrap Result(err) into ok")
    72  }
    73  
    74  func (r Result) UnwrapOr(v interface{}) interface{} {
    75  	if r.IsOk() {
    76  		return r.ok
    77  	}
    78  	return v
    79  }
    80  
    81  func (r Result) UnwrapOrElse(fn func(err error) interface{}) interface{} {
    82  	if r.IsOk() {
    83  		return r.ok
    84  	}
    85  	return fn(r.err)
    86  }