douyiken0968 2015-09-16 14:56
浏览 29
已采纳

组织/构造Go软件包文件夹和文件的正确方法是什么?

Hi guys I know this might be controversial or not very broad but I'm going to try to be very specific and relate to other questions.

Ok so when I make a Go program what things should I be thinking in terms of how I should organize my project? (E.g. should I think ok I'm going to have controllers of some sort so I should have a controller subdirectory that's going to do this so I should have that)

How should I structure a package?

For example the current program I'm working on I'm trying to make a SteamBot using this package

But while I'm writing it I don't know if I should export certain methods into their own own files, e.g. I'd have something like

func (t *tradeBot) acceptTrade() {}
func (t *tradeBot) declineTrade() {}
func (t *tradeBot) monitorTrade() {}
func (t *tradeBot) sendTrade() {}

each method is going to have quite a bit of code so should I export each method into its own file or just have 1 file with 3000 lines of code in it?

Also using global variables so that I can set one variable and then leave it and be able to use it in multiple functions, or is this bad and I should pass the variables as arguments?

Also should I order my files like:

package
imports
constants
variables
functions
methods

Or do I just put things where I need them

Hopefully I made myself clear and its not a terrible question. Thanks!

  • 写回答

2条回答 默认 最新

  • duanjitong7226 2015-09-16 15:09
    关注

    The first place to look for inspiration is the Go standard library. The Go standard library is a pretty good guide of what "good" Go code should look like. A library isn't quite the same as an application, but it's definitely a good introduction.

    In general, you would not break up every method into its own file. Go tends to prefer larger files that cover a topic. 3000 lines seems quite large, though. Even the net/http server.go is only 2200 lines, and it's pretty big.

    Global mutable variables are just as bad in Go as in any language. Since Go relies so heavily on concurrent programming, global mutable variables are quite horrible. Don't do that. One common exception is sync structures like sync.Pool or sync.Once, which sometimes are package global, but are also designed to be accessed concurrently. There are also sometimes "Default" versions of structures, like http.DefaultClient, but you can still pass explicit ones to functions. Again, look through the Go standard library and see what is common and what is rare.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部