Home > Backend Development > Golang > How to Parse a List of Values as a Flag in Golang?

How to Parse a List of Values as a Flag in Golang?

Patricia Arquette
Release: 2024-11-16 16:18:03
Original
957 people have browsed it

How to Parse a List of Values as a Flag in Golang?

Acquiring a List of Values as a Flag in Golang

In Golang, the standard flag package provides the ability to parse flags from the command line, but it inherently supports only primitive types such as strings, integers, and booleans. To handle a list of values as a flag, one can implement a custom flag.Value type and utilize flag.Var() for binding it.

An example implementation is available below:

import (
    "flag"
    "fmt"
)

type arrayFlags []string

// String is a required implementation of the flag.Value interface
func (i *arrayFlags) String() string {
    return fmt.Sprintf("%v", *i)
}

// Set is another required implementation of 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 parameter.")
    flag.Parse()
}
Copy after login

This custom flag type can then be used to pass multiple flag values, such as:

go run your_file.go --list1 value1 --list1 value2
Copy after login

In summary, by implementing a custom flag.Value type and utilizing flag.Var(), Golang allows developers to parse a list of values as flags, providing greater flexibility in command-line argument handling.

The above is the detailed content of How to Parse a List of Values as a Flag in Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template