golang 检查 cli 整数标志是否存在

问题描述 投票:0回答:3

当标志为布尔值时,我可以查看该标志是否存在。我试图弄清楚如何查看标志是否存在(如果是整数),如果确实存在,则使用该值(如果不忽略)。

例如,如果使用任一 Bool 标志,下面的代码就会执行某些操作。但我想为

-month
设置一个标志,即
go run appname.go -month=01
应该保存 01 的值,但如果不使用
-month
那么它应该像布尔标志一样被忽略。在下面的代码中,我通过设置默认值 0 来解决这个问题,因此如果没有使用
-month
标志,则该值为 0。有没有更好的方法来做到这一点?

package main

import (
    "flag"
    "fmt"
    "time"
)

func main() {
    //Adding flags
    useCron := flag.Bool("cron", false, "-cron, uses cron flags and defaults to true")
    useNow := flag.Bool("now", false, "-now, uses cron flags and defaults to true")
    useMonth := flag.Int("month", 0, "-month, specify a month")
    flag.Parse()

    //If -cron flag is used
    if *useCron {
        fmt.Printf("Cron set using cron run as date")
        return
    } else if *useNow {
        fmt.Printf("Use Current date")
        return
    }

    if *useMonth != 0 {
        fmt.Printf("month %v\n", *useMonth)
    }
}
go flags
3个回答
1
投票

请参阅

flag.Value
界面的文档和示例:

您可以定义一个自定义类型,它实现

flag.Value
,例如:

type CliInt struct {
    IsSet bool
    Val   int
}

func (i *CliInt) String() string {
    if !i.IsSet {
        return "<not set>"
    }
    return strconv.Itoa(i.Val)
}

func (i *CliInt) Set(value string) error {
    v, err := strconv.Atoi(value)
    if err != nil {
        return err
    }

    i.IsSet = true
    i.Val = v
    return nil
}

然后使用

flag.Var()
来绑定它:

    flag.Var(&i1, "i1", "1st int to parse")
    flag.Var(&i2, "i2", "2nd int to parse")

调用

flag.Parse()
后,您可以检查
.IsSet
标志以查看该标志是否已设置。

游乐场


另一种方法是在拨打flag.Visit()

之后再拨打
flag.Parse()
 :

    var isSet1, isSet2 bool

    i1 := flag.Int("i1", 0, "1st int to parse")
    i2 := flag.Int("i2", 0, "2nd int to parse")

    flag.Parse([]string{"-i1=123"})

    // flag.Visit will only visit flags which have been explicitly set :
    flag.Visit(func(fl *flag.Flag) {
        if fl.Name == "i1" {
            isSet1 = true
        }
        if fl.Name == "i2" {
            isSet2 = true
        }
    })

游乐场


0
投票

在 bool 标志中,您也无法检查是否存在,因为您正在检查默认的

false
值。如果您将其更改为
true
,您将始终获得现有的值。

useCron := flag.Bool("cron", true, "-cron, uses cron flags and defaults to true")
useNow := flag.Bool("now", true, "-now, uses cron flags and defaults to true")

对于任何其他数据类型也是如此,我们只能检查默认值。

您可以使用

flag.NFlag()

此函数返回 CLI 设置的许多标志。
当需要所有选项时,此选项才有意义。

@LeGEC 的答案满足您的要求。


0
投票

使用 https://github.com/cardinalby/go-struct-flags/ 您可以定义指针字段,如果未提供标志,则保留

nil

另一种方法是定义您自己的

flag.Value
,但这会阻止默认
Usage
打印标志类型和默认值。

使用

Visit
也是可以的,但不是很方便。

© www.soinside.com 2019 - 2024. All rights reserved.