dsozqcx9668 2012-09-01 19:17
浏览 54
已采纳

在golang中,“ net / http”对全局变量的使用是否被视为一种好习惯?

The golang package "net/http" uses the global variable DefaultServeMux to register handlers. Is this considered a good practice or even an golang idiom? Is it a global variable after all?

The two main reasons not to use global variables are AFAIK 1) that they add to complexity and 2) are problematic in concurrent programs.

Maybe 1) is not considered important in this case because the developer can choose not to use DefaultServerMux? What about 2)? Are global variables always thread/goroutine safe in Go? Still, I'm surprised that it's used in Go's standard library. I've never seen such practice in other languages / standard libraries.

  • 写回答

2条回答 默认 最新

  • dongmei8760 2012-09-09 00:46
    关注

    Is it a global variable after all?

    Yes. The variable is defined on root level, which makes it global throughout the package.

    However, this is not a global variable which stores all the sensible information of the net/http package. It is merely a convenience setup which uses the content of the net/http package to provide an quickstart opportunity to the user. This also means, that is does not add much complexity.

    Is this considered a good practice or even an golang idiom?

    IMO, it is good practice to aid the user with the usage of a package. If you're finding that you could save the user some time by providing a good default configuration, do so.

    However, you should be careful when you're about to export variables. They should be made ready for concurrent access. The DefaultServeMux (or better, the underlying ServeMux), for example, is using a mutex to be thread safe.

    Are global variables always thread/goroutine safe in Go?

    No. Without proper synchronization (mutex, channel, ...), everything that is accessed concurrently is problematic and will most certainly blow everything to bits and pieces.

    I've never seen such practice in other languages / standard libraries.

    Python's logging module, for example, provides a function to retrieve the root logging object, which one can call methods on to customize the logging behaviour. This could be seen as a global object, as it is mutable and defined in the module.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(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长安杯与连接网探