【问题标题】:How to limit the range of values acceptable in string flag?如何限制字符串标志中可接受的值范围?
【发布时间】:2020-04-13 14:13:02
【问题描述】:

我用这样的默认值声明一个字符串标志:

animalFlag := flag.String("typeOfAnimal", "Cat", "Type of animal")

我想强制用户只能给出一个特定的字符串(如"Dog""Lion"),而不是像"Rose" 这样的随机字符串。 如何在 Go 中强制执行此操作?

【问题讨论】:

    标签: go command-line-interface command-line-arguments


    【解决方案1】:

    flag 包不支持限制标志的有效/接受值集。

    您可以做的是执行标志值验证,这通常是一个很好的做法:在应用程序开始时检查值,如果提供的值无效(根据您的任意规则),则停止并显示错误消息.

    查看相关问题:Can command line flags in Go be set to mandatory?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 2019-02-21
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多