当使用”go run”命令时,避免输入主包中的所有go文件。

huangapple go评论86阅读模式
英文:

Avoid typing out all go files in the main package when "Go run"-ng

问题

当你在main包中有多个.go文件时,在执行go run命令时,需要将它们全部列出。

所以当我有main.goa.gob.go这三个文件,它们都属于main包,为了使用其他两个go文件中的函数和结构体,我需要输入go run main.go a.go b.go。然而,go build命令会自动智能地将所有文件链接在一起。

我是否对Go有什么误解,或者这种情况是正常的(在执行go run时列出main包中的所有文件)?

英文:

When you have multiple .go files in a main package, i need to list them all out when doing a go run.

So when i have main.go, a.go, b.go and they all belong to the main package, i need to type go run main.go a.go b.go in order to use functions and structs inside the other 2 go files. The go build command however, is smart enough to link all files together automatically.

Have i misunderstood something about Go, or is this normal (listing out all the files in the main package when doing a go run)?

答案1

得分: 4

简短回答是:你需要将它们全部列出来。如果你非常着急,你可以使用shell技巧来实现。通常我会编写一个shell脚本来进行go build,然后运行生成的可执行文件,当它变得太烦人时。

# 这个方法适用于没有_test.go文件的情况
go run *.go

# 如果你真的想要...启用扩展的glob
shopt -s extglob
# 这样你就可以做类似这样的事情(匹配除了*_test.go文件之外的所有.go文件)
go run !(*_test).go

请查看这个帖子:https://groups.google.com/forum/#!topic/golang-nuts/EOi0VAQNA4c

英文:

The short answer is: you need to list them all out. You can do this with shell tricks, if you're desperate. I usually just write a shell script to go build and then run the resulting executable, after it gets too annoying.

# this works unless you have _test.go files
go run *.go

# if you really want to... enable extended glob
shopt -s extglob
# so you can do something like this (matches all .go except *_test.go files)
go run !(*_test).go

Check out this thread: https://groups.google.com/forum/#!topic/golang-nuts/EOi0VAQNA4c

答案2

得分: 2

如果你的源代码位于$GOPATH/src目录下,例如:

$GOPATH/src/somedir/main.go
$GOPATH/src/somedir/a.go
$GOPATH/src/somedir/b.go

执行"go install somedir"命令将会编译并安装somedir二进制文件到$GOPATH/bin目录下,无需逐个列出文件。

"go install"命令会自动找到所有的文件。

我的常用Go工作流程是(在我的bash提示符下):
$ clear; go install myproj && $GOPATH/bin/myproj

这个命令会清屏,构建并安装"myproj",然后运行它。

所以,当我修改代码后,只需要按Ctrl-C,上箭头和回车键。

整个循环时间约为1秒(适用于小型项目)。

英文:

If your source is in $GOPATH/src
as in

$GOPATH/src/somedir/main.go
$GOPATH/src/somedir/a.go
$GOPATH/src/somedir/b.go

doing "go install somedir" will compile and install the somedir binary in to $GOPATH/bin

no need to list out the files individually

"go install" finds all the files on it's own.

My common work cycle with go is (from my bash prompt):
$ clear; go install myproj && $GOPATH/bin/myproj

which, clears the screen, builds and installs "myproj" and then runs it

so, after I change code, I just hit Ctrl-C, Up arrow, and enter.

Entire cycle time is ~1 second (for small to start stuff)

huangapple
  • 本文由 发表于 2014年1月4日 11:10:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/20916376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定