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

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

问题描述

注意:这个问题与这一个,但两年是Go历史上很长一段时间。



在开发过程中组织Go项目的标准方式是什么我的项目是一个单一的包 mypack ,所以我想我把所有的.go文件放在一个 code> mypack 目录。

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



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

解决方案

我会建议在如何编写Go Code

上查看此页面

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



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



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



因此,您的GOPATH可能会看起来像像这样:

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

export GOPATH = $ HOME / projects

  $ go build mypack 
$ go test mypack


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

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

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

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

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

解决方案

I would recommend reviewing this page on How to Write Go Code

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.

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 will then build into the root level pkg and bin.

So your GOPATH might look like this:

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

export GOPATH=$HOME/projects

$ go build mypack
$ go test mypack

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

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