duandushang5148 2013-08-25 13:47
浏览 314
已采纳

Go中的标志包-我是否必须始终设置默认值?

Is it possible not to set default value in flag package in Go? For example, in flag package you can write out the following line:

filename := flag.String("file", "test.csv", "Filename to cope with")

In the above code, I don't want to necessarily set default value, which is test.csv in this case, and instead always make users specify their own filename, and if it's not specified then I want to cause an error and exit the program.

One of the way I came up with is that I first check the value of filename after doing flag.Parse(), and if that value is test.csv then I have the program exits with the appropriate error message. However, I don't want to write such redundant code if it can be evaded - and even if it can't, I'd like to hear any better way to cope with the issue here.

You can do those kind of operations in Python's argparse module by the way - I just want to implement the similar thing if I can...

Also, can I implement both short and long arguments (in other words both -f and -file argument?) in flag package?

Thanks.

  • 写回答

2条回答 默认 最新

  • dongren1011 2013-08-25 14:25
    关注

    I think it's idiomatic to design your flag values in such a way which implies "not present" when equal to the zero value of their respective types. For example:

    optFile := flag.String("file", "", "Source file")
    flag.Parse()
    fn := *optFile
    if fn == "" {
            fn = "/dev/stdin"
    }
    f, err := os.Open(fn)
    ...
    

    Ad the 2nd question: IINM, the flag package by design doesn't distinguish between -flag and --flag. IOW, you can have both -f and --file in your flag set and write any version of - or -- before both f and file. However, considering another defined flag -g, the flag package will not recognize -gf foo as being equvalent of -g -f foo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档