Skip to content

Instantly share code, notes, and snippets.

@killwing
Last active April 17, 2026 15:34
Show Gist options
  • Select an option

  • Save killwing/067510b39b4f629f8b631a17989a409f to your computer and use it in GitHub Desktop.

Select an option

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
}
// Opt returns the value pointed to by p, or the zero value of T if p is nil.
func Opt[T any](p *T) (res T) {
if p != nil {
res = *p
}
return
}
// Or returns the value of p if it is not nil, otherwise it returns the def.
func Or[T any](p *T, def T) T {
if p != nil {
return *p
}
return def
}
// Ternary returns a if condition is true, otherwise b.
// Note: Both arguments are evaluated before the function is called.
// PANIC: Ternary(len(slice) > 0, slice[0], "default")
func Ternary[T any](condition bool, a,b T) T {
if condition {
return a
}
return b
}
@killwing

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment