Home >Backend Development >Golang >How to Parse List Values into Flags in Go?

How to Parse List Values into Flags in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 08:36:131027browse

How to Parse List Values into Flags in Go?

Parsing List Values into Flags in Go

In Go, the equivalent of Python's argparse is the flag package. While the built-in flag types support only strings, integers, and booleans, it is possible to define custom flag types to accommodate lists of values.

Custom Flag Type for Lists

To define a custom flag type for list values, implement the flag.Value interface in a new type, such as arrayFlags. The String() method provides a string representation of the list, and the Set() method updates the list with new values.

Binding the Custom Flag

Once you have defined the custom flag type, you can use flag.Var() to bind it to a flag. This allows you to pass multiple values for that flag at runtime.

Example Usage

Here's an example of how to use a custom flag type for lists:

package main

import (
    "flag"
    "fmt"
)

type arrayFlags []string

func (i *arrayFlags) String() string {
    return fmt.Sprintf("%v", *i)
}

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) // Prints [value1 value2]
}

Running this code with the following command will parse the list values into the myFlags variable:

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

The above is the detailed content of How to Parse List Values into Flags in Go?. 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