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.)

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

报告相同问题?