go run command-line-arguments

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 …
不然只编译你指定的文件啊

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值