Created
April 26, 2024 08:54
-
-
Save killwing/067510b39b4f629f8b631a17989a409f to your computer and use it in GitHub Desktop.
generic utils
This file contains 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 main | |
import ( | |
"encoding/json" | |
"fmt" | |
"os" | |
) | |
func bar() (int, error) { return 2, fmt.Errorf("testerr") } | |
func main() { | |
must(bar())("bar") | |
} | |
func must[T any](ret T, err error) func(s string) T { | |
return func(s string) T { | |
if err != nil { | |
fmt.Printf("%s failed: %s", s, err) | |
os.Exit(1) | |
} | |
return ret | |
} | |
} | |
func deepCopy[T any](de *T) *T { | |
b, _ := json.Marshal(de) | |
var ret T | |
_ = json.Unmarshal(b, &ret) | |
return &ret | |
} | |
// https://pkg.go.dev/cmp#Or | |
// Or returns the first of its arguments that is not equal to the zero value. | |
// If no argument is non-zero, it returns the zero value. | |
func Or[T comparable](vals ...T) T { | |
var zero T | |
for _, val := range vals { | |
if val != zero { | |
return val | |
} | |
} | |
return zero | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment