Custom Flag for Lists in Golang
Golang's flag package allows for easy argument parsing, but it typically supports basic types like string, integer, or boolean. This might seem limiting when working with lists of values.
Golang allows the creation of custom flags by implementing the flag.Value interface. This interface requires the implementation of two methods: String() and Set(). By defining a custom flag for lists, you can enable the parsing of multiple values passed through command-line flags.
Defining a Custom List Flag
Consider the following example:
package main import "flag" import "fmt" type arrayFlags []string // String() implements the flag.Value interface func (i *arrayFlags) String() string { return fmt.Sprintf("%v", *i) } // Set() implements the flag.Value interface 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() fmt.Println(myFlags) }
This defines a custom flag type called arrayFlags that accepts multiple values. The flag is bound to the "list1" flag name and can be parsed using flag.Parse().
Usage
To pass multiple values using this custom flag, you can run the program as follows:
go run your_file.go --list1 value1 --list1 value2 --list1 value3
This will populate the myFlags variable with the three provided values: ["value1", "value2", "value3"]. You can then access these values within your program.
Playground
For a live example, you can visit the following playground: [playground link]
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3