github.com/searKing/golang/go@v1.2.74/flag/string_slice.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package flag 6 7 import ( 8 "flag" 9 "fmt" 10 "sync" 11 ) 12 13 // StringSliceVarWithFlagSet defines a []string flag with specified name, default value, and usage string. 14 // The argument p points to a []string variable in which to store the value of the flag. 15 func StringSliceVarWithFlagSet(f *flag.FlagSet, p *[]string, name string, value []string, usage string) { 16 f.Var(newStringSliceValue(value, p), name, usage) 17 } 18 19 // StringSliceWithFlagSet defines an []string flag with specified name, default value, and usage string. 20 // The return value is the address of a []string variable that stores the value of the flag. 21 func StringSliceWithFlagSet(f *flag.FlagSet, name string, value []string, usage string) *[]string { 22 p := new([]string) 23 StringSliceVarWithFlagSet(f, p, name, value, usage) 24 return p 25 } 26 27 // StringSliceVar defines a []string flag with specified name, default value, and usage string. 28 // The argument p points to a []string variable in which to store the value of the flag. 29 func StringSliceVar(p *[]string, name string, value []string, usage string) { 30 flag.CommandLine.Var(newStringSliceValue(value, p), name, usage) 31 } 32 33 // StringSlice defines an []string flag with specified name, default value, and usage string. 34 // The return value is the address of a []string variable that stores the value of the flag. 35 func StringSlice(name string, value []string, usage string) *[]string { 36 return StringSliceWithFlagSet(flag.CommandLine, name, value, usage) 37 } 38 39 // stringSliceValue is a flag.Value that accumulates strings. 40 // e.g. --flag=one --flag=two would produce []string{"one", "two"}. 41 type stringSliceValue struct { 42 vars *[]string 43 once sync.Once 44 } 45 46 func newStringSliceValue(val []string, p *[]string) *stringSliceValue { 47 *p = val 48 return &stringSliceValue{vars: p} 49 //return (*stringSliceValue)(p) 50 } 51 52 func (ss *stringSliceValue) Get() interface{} { return *ss.vars } 53 54 func (ss *stringSliceValue) String() string { return fmt.Sprintf("%q", ss.vars) } 55 56 func (ss *stringSliceValue) Set(s string) error { 57 ss.once.Do(func() { 58 *(ss.vars) = nil 59 }) 60 *(ss.vars) = append(*(ss.vars), s) 61 return nil 62 }