如何访问传递给 Go 程序的命令行参数? [英] How to access command-line arguments passed to a Go program?
本文介绍了如何访问传递给 Go 程序的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Go 中访问命令行参数?它们不会作为参数传递给 main
.
How do I access command-line arguments in Go? They're not passed as arguments to main
.
一个完整的程序,可能是通过链接多个包创建的,必须有一个名为 main 的包,带有一个函数
A complete program, possibly created by linking multiple packages, must have one package called main, with a function
func main() { ... }
定义.函数 main.main() 不接受任何参数,也不返回任何值.
defined. The function main.main() takes no arguments and returns no value.
推荐答案
您可以使用 os.Args
变量.例如,
You can access the command-line arguments using the os.Args
variable. For example,
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(len(os.Args), os.Args)
}
您还可以使用 flag 包,它实现了命令行标志解析.
You can also use the flag package, which implements command-line flag parsing.
这篇关于如何访问传递给 Go 程序的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文