Home >Backend Development >Golang >How can I parse multiple values into a list using custom flags in Golang?

How can I parse multiple values into a list using custom flags in Golang?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 07:08:03338browse

How can I parse multiple values into a list using custom flags in Golang?

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]

The above is the detailed content of How can I parse multiple values into a list using custom flags in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn