Skip to content

Instantly share code, notes, and snippets.

@killwing
Created April 26, 2024 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killwing/067510b39b4f629f8b631a17989a409f to your computer and use it in GitHub Desktop.
Save killwing/067510b39b4f629f8b631a17989a409f to your computer and use it in GitHub Desktop.
generic utils
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