duanbai1370 2014-08-11 16:27
浏览 53
已采纳

为什么FlagSet无法正确解析这些参数?

Here's a simplified code snippet: the context for this in a real project is that I have a command-line app that's parsing arguments input to the program, and then individual commands that parse the remaining args after the command name is pulled out. I'm using a FlagSet per command, but for some reason, it won't ever actually parse out flags:

package main

import (
"fmt"
"flag"
)

func main() {
    args := []string{"arg", "-flag", "value"}
    flags := flag.NewFlagSet("flags", flag.ExitOnError)
    flagValue := flags.String("flag", "defaultValue", "")

    flags.Parse(args)
    fmt.Println(flags.Args(), *flagValue)

}

I'd expect the output to be: [arg] value, but instead I get: [arg -flag value] defaultValue

Code: http://play.golang.org/p/D4RKPpVODF

What am I doing wrong here?

  • 写回答

1条回答 默认 最新

  • dongshubang7816 2014-08-11 16:35
    关注

    The arguments in your args array are in the wrong order. The non-flag arguments have to come after the flag arguments. So you should write:

    args := []string{"-flag", "value", "arg"}
    

    Then the output is what you expected:

    [arg] value
    

    Code: http://play.golang.org/p/cv972SLZfG

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振
  • ¥20 pip2.40更新pip2.43时报错