15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goのflagパッケージで同名の引数を複数受け取る

Last updated at Posted at 2014-12-25

Goのflagパッケージで以下のようなことをやりたい。

test-cli --data value1 --data value2 --data value3

flag - The Go Programming

同じ名前の引数が複数登場する。

flagパッケージにはValueという型が用意されていて、これを満たす独自の型を用意してVar()に渡してあげる。

以下の例はでは、引数dataで指定された値をstringのスライスで受け取る実装です。[]stringを拡張した独自のstrslice型を用意して、flag.Valueを満たすためStirng()とSet()を実装しています。

package main

import (
	"flag"
	"fmt"
)

type strslice []string

func (s *strslice) String() string {
	return fmt.Sprintf("%v", multiflag)
}

func (s *strslice) Set(v string) error {
	*s = append(*s, v)
	return nil
}

var multiflag strslice

func main() {

	flag.Var(&multiflag, "data", "Data values.") 
	flag.Parse()

	fmt.Printf("%v", multiflag)
}

実行結果

$ ./test-cli --data value1 --data value2 --data value3
[value1 value2 value3]
15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?