| 1 |
// run |
| 2 |
|
| 3 |
// Copyright 2021 The Go Authors. All rights reserved. |
| 4 |
// Use of this source code is governed by a BSD-style |
| 5 |
// license that can be found in the LICENSE file. |
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
import ( |
| 10 |
"errors" |
| 11 |
"fmt" |
| 12 |
) |
| 13 |
|
| 14 |
type Option[T any] struct { |
| 15 |
ok bool |
| 16 |
val T |
| 17 |
} |
| 18 |
|
| 19 |
func (o Option[T]) String() string { |
| 20 |
if o.ok { |
| 21 |
return fmt.Sprintf("Some(%v)", o.val) |
| 22 |
} |
| 23 |
return "None" |
| 24 |
} |
| 25 |
|
| 26 |
func Some[T any](val T) Option[T] { return Option[T]{ok: true, val: val} } |
| 27 |
func None[T any]() Option[T] { return Option[T]{ok: false} } |
| 28 |
|
| 29 |
type Result[T, E any] struct { |
| 30 |
ok bool |
| 31 |
val T |
| 32 |
err E |
| 33 |
} |
| 34 |
|
| 35 |
func (r Result[T, E]) String() string { |
| 36 |
if r.ok { |
| 37 |
return fmt.Sprintf("Ok(%v)", r.val) |
| 38 |
} |
| 39 |
return fmt.Sprintf("Err(%v)", r.err) |
| 40 |
} |
| 41 |
|
| 42 |
func Ok[T, E any](val T) Result[T, E] { return Result[T, E]{ok: true, val: val} } |
| 43 |
func Err[T, E any](err E) Result[T, E] { return Result[T, E]{ok: false, err: err} } |
| 44 |
|
| 45 |
func main() { |
| 46 |
a := Some[int](1) |
| 47 |
b := None[int]() |
| 48 |
fmt.Println(a, b) |
| 49 |
|
| 50 |
x := Ok[int, error](1) |
| 51 |
y := Err[int, error](errors.New("test")) |
| 52 |
fmt.Println(x, y) |
| 53 |
// fmt.Println(x) |
| 54 |
_, _, _, _ = a, b, x, y |
| 55 |
} |