简体   繁体   English

递归编译文件

[英]Recursive compile files

I just started with Go, and i love it! 我刚开始用Go,我喜欢它! I have tried to make the structure of my project a bit more manageable, instead of having everything in my main.go 我试图让我的项目结构更易于管理,而不是在main.go中拥有所有内容

So now i have a structure like this. 所以现在我有这样的结构。

src/
-> main.go
-> routes.go
-> handlers/
--> user_handlers.go

But when i try to build this with the following command 但是当我尝试使用以下命令构建它时

go build -v -o ./bin/my_bin ./src/...

I get this error 我收到这个错误

cannot use -o with multiple packages

But if i make it a flat structure like this 但如果我把它做成这样的扁平结构

src/
-> main.go
-> routes.go
-> user_handlers.go

It works just fine, all my files got "package main" in the top of them. 它工作得很好,我的所有文件都在它们的顶部有“package main”。

What am i doing wrong? 我究竟做错了什么?

The package name must match the directory name. 包名称必须与目录名称匹配。 Moving a source file to a new directory requires that you also change the package name. 将源文件移动到新目录要求您还更改包名称。

foo/foo.go // package foo
foo/bar/bar.go // package bar
foo/bar/qux.go // package bar

The PATH is not relevant in terms of the package name. PATH与包名称无关。

Package foo: /some/path/some/where/foo 

This allows multiple "foo" packages to be created and imported provided your import specifies the desired location of "foo" 这允许创建和导入多个“foo”包,前提是您的导入指定了“foo”的所需位置

PS The convention for package names is lowercase, no punctuation (eg, no _'s) PS包名称的约定是小写,没有标点符号(例如,没有_的)

It tells you what you did wrong, you can't separate a single package over multiple folders. 它告诉你你做错了什么,你不能将单个包分成多个文件夹。

You need to set and properly use $GOPATH and properly import your routes/ folder in routes.go . 您需要设置和正确使用$GOPATH和正确导入您的routes/文件夹routes.go

A simple example of it is: 一个简单的例子是:

// routes.go
// the . means you can call imported functions without prefixing them with the package name
import . "full-path-to-routes/-relative-to-$GOPATH"

From https://golang.org/doc/code.html : 来自https://golang.org/doc/code.html

The GOPATH environment variable specifies the location of your workspace. GOPATH环境变量指定工作区的位置。 It is likely the only environment variable you'll need to set when developing Go code. 它可能是开发Go代码时需要设置的唯一环境变量。

To get started, create a workspace directory and set GOPATH accordingly. 首先,创建一个工作区目录并相应地设置GOPATH。 Your workspace can be located wherever you like, but we'll use $HOME/go in this document. 您的工作区可以放在任何您喜欢的位置,但我们将在本文档中使用$ HOME / go。 Note that this must not be the same path as your Go installation. 请注意,这与Go安装的路径不能相同。

I highly recommend reading Effective Go . 我强烈推荐阅读Effective Go

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM