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
Release: 2024-11-16 18:13:03
Original
994 people have browsed it

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
}
Copy after login

Using the Custom Flag

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

var myFlags arrayFlags
Copy after login

Registering the Custom Flag

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

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

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

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

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()
}
Copy after login

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!

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