Home >Backend Development >Golang >How to Define a Custom Flag Type for a List of Values in Go?

How to Define a Custom Flag Type for a List of Values in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 18:13:03996browse

How to Define a Custom Flag Type for a List of Values in Go?

Getting a List of Values into a Flag in Go

In Go, the flag package supports parsing command-line arguments. However, it initially provided only a limited range of data types (String, Int, Bool). To accommodate more complex data, you can define your own flag type and use flag.Var() to bind it.

Custom Flag Type for List

Consider a flag that accepts multiple values as a list. First, define a custom flag type:

type arrayFlags []string

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

// Set is an implementation of the flag.Value interface
func (i *arrayFlags) Set(value string) error {
    *i = append(*i, value)
    return nil
}

Using the Custom Flag

Next, declare a variable of this type to bind with the custom flag:

var myFlags arrayFlags

Registering the Custom Flag

Finally, you can register your custom flag with the flag package:

flag.Var(&myFlags, "list1", "Some description for this param.")

Now, you can pass multiple values to this flag when running your program:

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

Updated Code Snippet

For reference, here is the complete code snippet:

package main

import (
    "flag"
    "fmt"
)

type arrayFlags []string

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

// Set is an 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 param.")
    flag.Parse()
}

The above is the detailed content of How to Define a Custom Flag Type for a List of Values 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