如何访问传递给Go程序的命令行参数? [英] How to access command-line arguments passed to a Go program?

查看:103
本文介绍了如何访问传递给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)
}

您也可以使用标志包,它实现了命令行标志解析。

You can also use the flag package, which implements command-line flag parsing.

这篇关于如何访问传递给Go程序的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆