首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何访问传递给Go程序的命令行参数?

如何访问传递给Go程序的命令行参数?
EN

Stack Overflow用户
提问于 2010-04-25 14:55:27
回答 6查看 53.4K关注 0票数 99

如何在Go中访问命令行参数?它们不会作为参数传递给main

一个完整的程序(可能是通过链接多个包创建的)必须有一个名为main的包,其中包含一个函数

func main() { ... }

已定义。函数main.main()不接受任何参数,也不返回值。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2010-04-25 15:16:53

您可以使用os.Args变量访问命令行参数。例如,

代码语言:javascript
复制
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(len(os.Args), os.Args)
}

您还可以使用flag package,它实现了命令行标志解析。

票数 122
EN

Stack Overflow用户

发布于 2016-12-03 06:53:20

Flag就是一个很好的包。

代码语言:javascript
复制
package main

// Go provides a `flag` package supporting basic
// command-line flag parsing. We'll use this package to
// implement our example command-line program.
import "flag"
import "fmt"

func main() {

    // Basic flag declarations are available for string,
    // integer, and boolean options. Here we declare a
    // string flag `word` with a default value `"foo"`
    // and a short description. This `flag.String` function
    // returns a string pointer (not a string value);
    // we'll see how to use this pointer below.
    wordPtr := flag.String("word", "foo", "a string")

    // This declares `numb` and `fork` flags, using a
    // similar approach to the `word` flag.
    numbPtr := flag.Int("numb", 42, "an int")
    boolPtr := flag.Bool("fork", false, "a bool")

    // It's also possible to declare an option that uses an
    // existing var declared elsewhere in the program.
    // Note that we need to pass in a pointer to the flag
    // declaration function.
    var svar string
    flag.StringVar(&svar, "svar", "bar", "a string var")

    // Once all flags are declared, call `flag.Parse()`
    // to execute the command-line parsing.
    flag.Parse()

    // Here we'll just dump out the parsed options and
    // any trailing positional arguments. Note that we
    // need to dereference the pointers with e.g. `*wordPtr`
    // to get the actual option values.
    fmt.Println("word:", *wordPtr)
    fmt.Println("numb:", *numbPtr)
    fmt.Println("fork:", *boolPtr)
    fmt.Println("svar:", svar)
    fmt.Println("tail:", flag.Args())
}
票数 15
EN

Stack Overflow用户

发布于 2010-04-25 15:08:20

命令行参数可以在os.Args中找到。不过,在大多数情况下,flag包更好,因为它可以为您解析参数。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2707434

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档