我刚开始将 Go 用于一个简单的 Web 编程项目,但我不太清楚如何完成单个函数本地的简单预计算。这是我在 OCaml 中经常做的事情,例如:
(* 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]
对于那些不熟悉 OCaml 的人,上面发生的事情是我将名称 render_page
绑定(bind)到一个函数,该函数采用两个参数并可能返回一个网页,但在内部我首先创建一个本地绑定(bind)到 templ
(此绑定(bind)仅在 render_page
的定义中可见,并且计算仅发生一次)然后在匿名函数中使用该绑定(bind),这是实际的值绑定(bind)到 render_page
。因此,当您调用 render_page
时,templ
不会每次都重新编译:它只是从闭包环境中获取。
在 Go 中是否有一个通用的模式来完成这样的事情?我想尽可能避免使用全局变量。我知道“全局”变量可能仅限于包的 namespace ,这是我目前正在做的,但我想将这些预先计算的表达式的可见性限制在需要它们的函数中.
谢谢!
最佳答案
不熟悉 Ocaml,所以不能 100% 确定这个 Go 示例是否是您正在寻找的,但是您可以在 Go 中定义一个函数,它可以预先计算一些东西,然后返回一个内部使用预计算的匿名函数计算值。
例如,如果您这样做:
func matcher(pattern string) func(string) bool {
regExp := regexp.MustCompile(pattern)
return func(s string) bool {
return regExp.MatchString(s)
}
}
然后通过执行以下操作创建其中一个函数:
myMatcher := matcher("123")
然后可以多次调用myMatcher("something")
,正则表达式不会每次都编译,因为在调用matcher
函数时已经编译过了.
这是一个可用的 Go playground:
关于go - 在 Go 中为函数预计算简单值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44337071/