go run command-line-arguments
1.复现
目录结构:
$ tree test1280
test1280
|-- go.mod
|-- hello.go
`-- main.go
代码内容:
/*go.mod*/
module test1280
go 1.16
/*hello.go*/
package main
import "fmt"
func Hello() {
fmt.Println("hello,test1280!")
}
/*main.go*/
package main
func main() {
Hello()
}
执行过程:
$ go run main.go
# command-line-arguments
./main.go:4:2: undefined: Hello
$ ls -l
total 12
-rw-rw-r-- 1 jiang jiang 25 May 26 09:44 go.mod
-rw-rw-r-- 1 jiang jiang 79 May 26 11:09 hello.go
-rw-rw-r-- 1 jiang jiang 39 May 26 11:09 main.go
出现报错:
# command-line-arguments
./main.go:4:2: undefined: Hello
但是,在IDE(idea-goland)中没有提示报错:
注意,执行 go run main.go 将出错,但是以下命令可以正确执行:
$ go run test1280
hello,test1280!
或者:
$ go build && ./test1280
hello,test1280!
2.解决
执行命令:
$ go run main.go hello.go
hello,test1280!
或者:
$ go run .
hello,test1280!
或者:
$ go run *.go
hello,test1280!
3.原因
go run 时,会先编译命令行输入的所有go文件集合生成可执行文件然后执行之。
注意,go run 时,编译的是命令行参数输入的go文件,之前错误的命令是:
go run main.go
实际上main.go依赖于hello.go文件,因此,仅从main.go中找不到Hello函数,undefined。
正确方法:
a.在go run时传入所有的依赖的go文件,例如:
/* solution1 */
go run main.go hello.go
/* solution2 */
go run .
/* solution3 */
go run *.go
b.在go run时传入module而非go文件,例如:
$ go run test1280
hello,test1280!
# go run <module name>,本例中module name是test1280,参见go.mod文件
c.用go build替代go run,例如:
$ go build && ./test1280
hello,test1280!
# go build && ./<module name>,本例中生成的可执行文件是test1280
4.参考
https://www.jianshu.com/p/6a6e3e7b7c83
采用go run命令执行的时候,需要把待加载的.go文件都包含到参数里面。
https://groups.google.com/g/golang-nuts/c/JlWcLcw5eLI/m/qhu27ll3AgAJ
“go run” builds and runs what you tell it: only main.go.
https://www.codercto.com/a/52404.html
https://studygolang.com/topics/9270
go run *.go …
不然只编译你指定的文件啊