dsfykqq3403 2013-11-04 05:09
浏览 50
已采纳

在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:

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.

  • 写回答

1条回答 默认 最新

  • duanaixuan7385 2013-11-04 05:40
    关注

    This is complicated example of using flag package. 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)
    }       
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大