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

发布于 2025-01-10 08:18:31 字数 982 浏览 0 评论 0原文

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

例如,如果使用任一 Bool 标志,下面的代码会执行某些操作。但我想为 -month 设置一个标志,即 go run appname.go -month=01 应该保存 01 的值,但如果 -month code> 没有被使用,那么它应该像 bool 标志一样被忽略。在下面的代码中,我通过设置默认值 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)
    }
}

I'm able to see if a flag exists when its a bool. I'm trying to figure out how to see if a flag exits if its integer, if it does exist use the value if not ignore.

For example, the code below does something if either Bool flags are used. BUT I want to set a flag for -month ie go run appname.go -month=01 should then save the value of 01 but if -month is not used then it should be ignored like a bool flag. In the code below I got around this by making a default value of 0 so if no -month flag is used the value is 0. Is there a better way to do this?

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)
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

Smile简单爱 2025-01-17 08:18:31

请参阅 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 标志以查看该标志是否已设置。

playground


另一种方法是调用 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
        }
    })

游乐场

See the documentation and example for the flag.Value interface :

You may define a custom type, which implements flag.Value, for example :

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
}

and then use flag.Var() to bind it :

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

after calling flag.Parse(), you may check the .IsSet flag to see if that flag was set.

playground


Another way is to call flag.Visit() after calling 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
        }
    })

playground

浪推晚风 2025-01-17 08:18:31

在 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 答案满足您的要求。

In the bool flag also you can't check if exist or not because you are checking the default false value. If you will change it to true you will always get it as exists.

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")

The same goes for any other data type, we can only check the default values.

You can use flag.NFlag().
This function returns a number of flags set by the CLI.
This option makes sense when all the options are required.

@LeGEC answer fulfills your requirement.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文