How to get a list of values into a flag in Golang?

后端 未结 4 1234
失恋的感觉
失恋的感觉 2020-12-13 03:53

What is Golang\'s equivalent of the below python commands ?

import argparse
parser = argparse.ArgumentParser(description=\"something\")
parser.add_argument(\         


        
相关标签:
4条回答
  • 2020-12-13 03:57

    Use flag.String() to get the entire list of values for the argument you need and then split it up into individual items with strings.Split().

    0 讨论(0)
  • 2020-12-13 04:11

    You can at least have a list of arguments on the end of you command by using the flag.Args() function.

    package main
    
    import (
        "flag"
        "fmt"
    )
    
    var one string
    
    func main() {
        flag.StringVar(&one, "o", "default", "arg one")
        flag.Parse()
        tail := flag.Args()
        fmt.Printf("Tail: %+q\n", tail)
    }
    

    my-go-app -o 1 this is the rest will print Tail: ["this" "is" "the" "rest"]

    0 讨论(0)
  • 2020-12-13 04:12

    If you have a series of integer values at the end of the command line, this helper function will properly convert them and place them in a slice of ints:

    package main
    
    import (
        "flag"
        "fmt"
        "strconv"
    )
    
    func GetIntSlice(i *[]string) []int {
        var arr = *i
        ret := []int{}
        for _, str := range arr {
            one_int, _ := strconv.Atoi(str)
            ret = append(ret, one_int)
        }
        return ret
    }
    
    func main() {
        flag.Parse()
        tail := flag.Args()
        fmt.Printf("Tail: %T,  %+v\n", tail, tail)
        intSlice := GetIntSlice(&tail)
    
        fmt.Printf("intSlice: %T,  %+v\n", intSlice, intSlice)
    
    }
    
    mac:demoProject sx$ go run demo2.go 1 2 3 4
    Tail: []string,  [1 2 3 4]
    intSlice: []int,  [1 2 3 4]
    
    0 讨论(0)
  • 2020-12-13 04:15

    You can define your own flag.Value and use flag.Var() for binding it.

    The example is here.

    Then you can pass multiple flags like following:

    go run your_file.go --list1 value1 --list1 value2
    

    UPD: including code snippet right there just in case.

    package main
    
    import "flag"
    
    type arrayFlags []string
    
    func (i *arrayFlags) String() string {
        return "my string representation"
    }
    
    func (i *arrayFlags) Set(value string) error {
        *i = append(*i, value)
        return nil
    }
    
    var myFlags arrayFlags
    
    func main() {
        flag.Var(&myFlags, "list1", "Some description for this param.")
        flag.Parse()
    }
    
    0 讨论(0)
提交回复
热议问题