Skip to content

Instantly share code, notes, and snippets.

@GeertJohan
Last active December 12, 2015 05:28
Show Gist options
  • Save GeertJohan/4721912 to your computer and use it in GitHub Desktop.
Save GeertJohan/4721912 to your computer and use it in GitHub Desktop.
Idea for a Go `must()` builtin or `must` keyword.
// Some functions to demonstrate the idea of must()
func zero() error {
return nil
}
func one() int, error {
return 1, nil
}
func two() string, int, error {
return "two", 2, nil
}
// Without must(), we could do something like this. I do this all the time in initialisation and setup.
err := zero() // no return value except for the error we should check
if err !=nil {
panic(err)
}
a, err := one() // one return value plus an error we should check
if err != nil {
panic(err)
}
a, b, err := two() // two return values plus an error we should check
if err != nil {
panic(err)
}
// With must():
must(zero()) // no return values, panics on error
a := must(one()) // one return value, panics on error
a, b := must(two()) // two return values, panics on error
// Why builtin?
// Because only that way it will fit on any function signature, no matter what the return values are besides the error.
// must() will only accept return values from a function that have at least one error
// Another idea could be to make must a keyword instead of a builtin function. like this:
must zero()
a := must one()
a, b := must two()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment