douchenbiao0916 2017-11-16 21:34
浏览 137
已采纳

在包中定义共享变量-Go

I have a package with multiple go files in it, I am looking for best practices to follow when using these variables

var print string

type someStruct struct {
  //some vars
}

Consider package files has following go files in it

file1.go has a string variable print

file2.go has a struct someStruct

file3.go needs a string variable print

file4.go needs a struct someStruct

should I access/use the variable from file1.go in file3.go or create a new string variable i.e., file3print

same way should I access/use the someStruct from file2.go in file4.go or create a new struct i.e., file3SomeStruct

  • 写回答

1条回答 默认 最新

  • duaevb1511 2017-11-17 00:10
    关注

    Do not create file-specific types, nor variables, a la file3SomeStruct, just for the sake of avoiding sharing of those identifiers between files, a practice like this seems to me very unreasonable and would most definitely be considered bad practice.

    Sharing of identifiers between files is absolutely ok and you can find countless examples of this practice in the standard library.

    Just take a look through the net/http package source files.

    If you want, you can think of packages as representing a single-concept, e.g. HTTP, and the package's files representing its sub-concepts, like an HTTP server, HTTP client, or HTTP request. But for the HTTP to be useful its sub-concepts need to be able to interact. (This is not a required standard, some packages may be better off with a different design.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?