douwen3836 2015-04-21 17:05
浏览 47
已采纳

惯用的Go代码组织

Note: I've seen other questions related to this topic but none that address the issue at hand.

I'm struggling to organize my Go code. I'm writing a daemon and I would like to split the code logically between files.

Say I have 3 files, main.go:

package main

func main() {
    GlobalFunc()

    commonFunc()

    var svr server.Server
    server.OtherFunc()
}

server.go:

package main

type Server struct {
    name string
    ip string
}

func GlobalFunc() {

}

func (s *Server) OtherFunc() {
    commonFunc()
}

and common.go:

package main

func commonFunc() {

}

I would like to be able to call GlobalFunc() as server.GlobalFunc() to show it's part of the "server module". That doesn't seem possible with the above example.

I could make a subdir server, put server.go in there, and change it to package server. The problem here is that I can't seem to shared common.go between the main and the server package. I understand why, it doesn't seem like a good idea either.

So I am missing something simple here and making this more complicated?

Thanks!

  • 写回答

1条回答 默认 最新

  • dpgbh20688 2015-04-21 17:48
    关注

    I think it's fair assumption you'd like to use some common methods across your projects. The same way you separate the server, you should then separate the package with the common methods. Although it's probably better to think and organise it in some logical way, rather than calling the package tools, misc etc.

    I tend to split things into packages, so they can be used in other places, while the main package would be simply flag parsing and calling the library methods, for example server.Run(). Other people like to put everything into the main project, which might be all right if you think people would use your project as a command line tool, rather than a package.

    I would consider:

    deamon/
        main.go
        server/server.go
        somelib/somelib.go -- to be included from main and server
    

    If you would like your project to be used mainly as a package, but still include some command line utility, you might consider:

    deamon/
       deamon.go -- package deamon
       deamond/
           main.go -- you may include the top level package as anyone else
    

    We need to remember that in Go you include your packages with an absolute path, so you can keep your "common" stuff anywhere in the project, or if you decide is useful by itself, just release a separate, standalone project.

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

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了