Precomputing simple values for a function in Go

Viewed 151

I just started using Go for a simple web programming project, but I can't quite figure out how to accomplish simple pre-computation local to a single function. This is something I do quite frequently in OCaml, e.g.:

(* maybe render_page is a handler function for an HTTP server or something *)
let render_page =
  (* let's say that Template.prepare takes a template string and returns its compiled representation *)
  let templ = Template.prepare "user: {{.}}, group: {{.}}" in
  (* return an anonymous function *)
  fun user group ->
    templ [user; group]

For those unfamiliar with OCaml, what's happening above is I'm binding the name render_page to a function that takes two parameters and presumably returns a web page, but internally I'm first creating a local binding to templ (this binding is only visible within the definition of render_page, and the computation only happens once) and then using that binding within an anonymous function, which is the actual value bound to render_page. So when you call render_page, templ isn't recompiled every time: it's just fetched from the closure environment.

Is there a common pattern for accomplishing something like this in Go? I'd like to avoid global variables as much as possible. I'm aware that "global" variables may be confined to a package's name space, which is what I'm currently doing, but I'd like to restrict the visibility of these precomputed expressions to just the functions in which they're needed.

Thanks!

3 Answers
Related