组织多文件 Go 项目 [英] Organizing a multiple-file Go project

查看:30
本文介绍了组织多文件 Go 项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这个问题与这个,但两年在围棋历史上是很长的时间.

Note: this question is related to this one, but two years is a very long time in Go history.

在开发过程中组织 Go 项目的标准方法是什么?

What is the standard way to organize a Go project during development ?

我的项目是一个单独的包 mypack,所以我想我把所有的 .go 文件放在了一个 mypack 目录中.

My project is a single package mypack, so I guess I put all the .go files in a mypack directory.

但是,我想在开发过程中测试它,所以我至少需要一个声明 main 包的文件,以便我可以执行 go run trypack.go

But then, I would like to test it during development so I need at least a file declaring the main package, so that I can do go run trypack.go

我应该如何组织这个?每次我想尝试时都需要 go install mypack 吗?

How should I organize this ? Do I need to do go install mypack each time I want to try it ?

推荐答案

我建议在 How 上查看此页面编写 Go 代码

它记录了如何以 go build 友好的方式构建您的项目,以及如何编写测试.测试不需要是使用 main 包的 cmd.它们可以简单地将 TestX 命名函数作为每个包的一部分,然后 go test 会发现它们.

It documents both how to structure your project in a go build friendly way, and also how to write tests. Tests do not need to be a cmd using the main package. They can simply be TestX named functions as part of each package, and then go test will discover them.

您问题中该链接中建议的结构有点过时,现在随着 Go 1 的发布.您不再需要在 srcpkg 目录>.只有 3 个与规范相关的目录是 GOPATH 根目录中的 3 个: bin, pkg, src .在 src 下面,你可以简单地放置你的项目 mypack,在它下面是你所有的 .go 文件,包括 mypack_test.go

The structure suggested in that link in your question is a bit outdated, now with the release of Go 1. You no longer would need to place a pkg directory under src. The only 3 spec-related directories are the 3 in the root of your GOPATH: bin, pkg, src . Underneath src, you can simply place your project mypack, and underneath that is all of your .go files including the mypack_test.go

go build 然后将构建到根级别的 pkg 和 bin 中.

go build will then build into the root level pkg and bin.

所以你的 GOPATH 可能是这样的:

So your GOPATH might look like this:

~/projects/
    bin/
    pkg/
    src/
      mypack/
        foo.go
        bar.go
        mypack_test.go

导出 GOPATH=$HOME/projects

$ go build mypack
$ go test mypack

更新:从 >= Go 1.11 开始,Module 系统现已成为标准部分工具和 GOPATH 概念即将过时.

Update: as of >= Go 1.11, the Module system is now a standard part of the tooling and the GOPATH concept is close to becoming obsolete.

这篇关于组织多文件 Go 项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆