简体   繁体   English

在golang中标记命令行解析

[英]Flag command line parsing in golang

I'm not sure I understand the reasoning behind this example (taken from here ), nor what it is trying to communicate about the Go language: 我不确定我理解这个例子背后的原因(从这里开始 ),也不知道它试图传达的关于Go语言的内容:

package main

import (
    "flag"
    "fmt"
)

func main() {
    f := flag.NewFlagSet("flag", flag.ExitOnError)
    f.Bool("bool", false, "this is bool flag")
    f.Int("int", 0, "this is int flag")

    visitor := func(a *flag.Flag) {
        fmt.Println(">", a.Name, "value=", a.Value)
    }

    fmt.Println("Visit()")
    f.Visit(visitor)
    fmt.Println("VisitAll()")
    f.VisitAll(visitor)

    // set flags
    f.Parse([]string{"-bool", "-int", "100"})

    fmt.Println("Visit() after Parse()")
    f.Visit(visitor)
    fmt.Println("VisitAll() after Parse()")
    f.VisitAll(visitor)
}

Something along the lines of the setup they have but then adding a 他们有一些设置,但随后添加了一个

int_val := f.get("int")

to get the named argument would seem more useful. 获得命名参数似乎更有用。 I'm completely new to Go, so just trying to get acquainted with the language. 我是Go的新手,所以只是试着熟悉这门语言。

This is complicated example of using flag package. 这是使用flag包的复杂示例。 Typically flags set up this way: 通常以这种方式设置标志:

package main

import "flag"

// note, that variables are pointers
var strFlag = flag.String("long-string", "", "Description")
var boolFlag = flag.Bool("bool", false, "Description of flag")

func init() {
    // example with short version for long flag
    flag.StringVar(strFlag, "s", "", "Description")
}

func main() {
    flag.Parse()
    println(*strFlag, *boolFlag)
}       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM