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

后端 未结 4 1239
失恋的感觉
失恋的感觉 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条回答
  •  旧时难觅i
    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]
    

提交回复
热议问题