dongpiao8821 2017-06-02 20:36
浏览 82
已采纳

在Go中为函数预计算简单值

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条回答 默认 最新

  • douzhuo6931 2017-06-02 20:58
    关注

    Not familiar with Ocaml so not 100% sure if this Go example is what you are looking for, but you can define a function in Go which can pre-calculate some stuff and then return an anonymous function that internally uses the pre-calculated values.

    For example, if you do this:

    func matcher(pattern string) func(string) bool {
        regExp := regexp.MustCompile(pattern)
        return func(s string) bool {
            return regExp.MatchString(s)
        }
    }
    

    And then create one of these functions by doing:

    myMatcher := matcher("123")
    

    You can then call myMatcher("something") multiple times, and the regexp expression will not be compiled each time since it was already compiled when calling the matcher function.

    Here's a working Go playground with this:

    https://play.golang.org/p/m3vBrYn4Dg

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测