douniao8687 2015-09-01 11:37
浏览 36
已采纳

如何找到来自Golang控制台的标志数量

I'm passing argument from console. There are some flags too. Like:

go run test.go "-IP=10.10.10.10" "-db=kite" "-wv=45" "-cv=75" "A = value1" "B = value2" "C = 100" "D := ((A-B)/A)*C" "D ?"

Here, -IP, -db, -wv, -wc these four are flags and others are passing as normal argument as I know.

Number of flags can be variable.

How can I know how many flags are passed to my program. In this case 4 flags are passed.

  • 写回答

1条回答 默认 最新

  • doouzlrvb01417498 2015-09-01 11:46
    关注

    If you use the standard flag package to parse command-line flags, you can call the NFlag function to get the number of flags:

    package main
    import "fmt"
    import "flag"
    
    func main() {
            flag.Bool("a", true, "A value");
            flag.Bool("b", true, "B value");
            flag.Parse();
    
            fmt.Println(flag.NFlag())
    }
    

    Test:

    $ go run test.go 
    0
    $ go run test.go -a
    1
    $ go run test.go -a -b
    2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?