Skip to content

Instantly share code, notes, and snippets.

@l0k18
Last active March 1, 2019 22:02
Show Gist options
  • Save l0k18/51d23c289661669871587d6991b843f4 to your computer and use it in GitHub Desktop.
Save l0k18/51d23c289661669871587d6991b843f4 to your computer and use it in GitHub Desktop.
Using functions in Go declarations

Using functions in Go declarations

The best way to approach the limitations of Go's type system in regards to the function signature and closures, is to simply use variables. This also gives you something you can set to nil to become a typed nil, which is quite nasty syntax also.

var DefaultHandler = func(s string) error {
  return nil
}

then you can use this:

var ConfigTree = Config{
  Name: "somename",
  Handler: DefaultHandler,
}

func main() {
  if err := ConfigTree.Handler("testing"); err != nil {
    panic(err)
  }
  ConfigTree = nil
  if ConfigTree != nil {
    panic("this cannot happen") // expect linter to say so
  }
}

This lets you DRY out some of your Go code :)

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