英文:
Passing CLI arguments to excutables with 'go run'
问题
我有一个程序readfile.go
,我想将命令行参数os.Args[1]
也设置为readfile.go
。
然而,'go run'认为这是它自己的附加参数,而不是输出可执行文件的参数。是否有一个标志可以告诉'go run'这是可执行文件的参数?
mvaidya@mvaidya-VirtualBox:~/junkeork$ go run readfile.go readfile.go package main: case-insensitive file name collision: "readfile.go" and "readfile.go" mvaidya@mvaidya-VirtualBox:~/junkeork$
错误信息:
package main: case-insensitive file name collision: "readfile.go" and "readfile.go"
英文:
I have a program readfile.go
and I want to give the command line argument os.Args[1]
also as readfile.go
.
However 'go run' thinks that it is an additional argument to itself rather than to the output executable. Is there a flag which can tell 'go run' that this is an argument to executable?
<pre>
mvaidya@mvaidya-VirtualBox:~/junkeork$ go run readfile.go readfile.go
package main: case-insensitive file name collision: "readfile.go" and "readfile.go"
mvaidya@mvaidya-VirtualBox:~/junkeork$
</pre>
Error:
> package main: case-insensitive file name collision: "readfile.go" and
> "readfile.go"
答案1
得分: 29
你可以使用--
来将go文件与参数分开:
go run readfile.go -- readfile.go
英文:
You can use --
to separate gofiles from arguments:
go run readfile.go -- readfile.go
答案2
得分: 8
为了避免获取两次readfile.go
的歧义,我建议你使用命名的标志。这也会解决这个问题。
示例:
package main
import (
"flag"
"fmt"
)
func main() {
cmd := flag.String("cmd", "", "")
flag.Parse()
fmt.Printf("my cmd: \"%v\"\n", string(*cmd))
}
不要忘记使用flag.Parse()
来获取命令行参数
你可以通过以下方式将参数传递给go run
命令:go run .\main.go -cmd main.go
,然后你将得到输出:
my cmd: "main.go"
希望这能帮到其他人。
英文:
To avoid the ambiguity of getting twice readfile.go
, I advise you to use named flags. This will solve the problem too.
Example:
package main
import (
"flag"
"fmt"
)
func main() {
cmd := flag.String("cmd", "", "")
flag.Parse()
fmt.Printf("my cmd: \"%v\"\n", string(*cmd))
}
Don't forget using flag.Parse()
to retrieve the command line arguments
You can pass args to the go run
command this way: go run .\main.go -cmd main.go
and you'll get as output:
my cmd: "main.go"
I hope this can help other.
答案3
得分: 1
janos的答案对于未命名的参数可以很好地工作,对于命名参数:
go run .go -arg1Name arg1Value -arg2Name arg2Value.....
例如,go run main.go -x 2 -y 5;x和y是参数名称。
英文:
The answer by janos can work well with unnamed args., for named args.:
go run .go -arg1Name arg1Value -arg2Name arg2Value.....
Eg, go run main.go -x 2 -y 5 ; x and y are arg. names
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论