duanmao1319 2014-12-01 10:03
浏览 42
已采纳

如何在Go中使用未共享的有状态变量?

I know that, right now (and probably forever), we won't have static variables in Go... but is there a way to protect variables in some way?

import (
    "net/http"
    "net/http/cookiejar"
)

func funcThatDoesRequests(request Request) (response Response, e error){
  static cookieJar, _ := cookiejar.New(nil)
  static client := http.Client{ Jar: cookieJar }
  response, e = client.Do(handshakeRequest)
  return
}

I don't want the http client and its cookieJar floating around so other functions can do something with them. I need the cookieJar and client to only be accessible inside the funcThatDoesRequests. Is that possible?

Static variables (see static keyword in the pseudo code example) is a feature present in languages like C and PHP, to name some common languages.

  • 写回答

2条回答 默认 最新

  • duanmeng1862 2014-12-01 10:16
    关注

    Usually it's best not to worry about package-scoped globals since it's only code in your own package that can abuse them.

    But if you really want, you can use a closure which is created when your package is loaded to generate the "static" variables.

    func makeFunc() func(req Request)(Response, error) {
        cookieJar, _ := cookiejar.New(nil)
        client := http.Client{Jar: cookieJar}
        return func(req Request)(Response, error) {
            return client.Do(handshakeRequest)
        }
    }
    
    var funcThatDoesRequests = makeFunc()
    

    Now funcThatDoesRequests maintains client and cookieJar over multiple calls, but the names don't leak into the package.

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

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探