Golang flag.Var() function example
package flag
Var defines a flag with the specified name(2nd parameter) and usage string(3rd parameter). The type and value(1st parameter) of the flag are represented by the first argument, of type Value, which typically holds a user-defined implementation of Value. For instance, the caller could create a flag that turns a comma-separated string into a slice of strings by giving the slice the methods of Value; in particular, Set would decompose the comma-separated string into the slice.
Golang flag.Var() function usage example
package main
import (
"flag"
"fmt"
)
type flagStr struct {
value *string
}
func (f *flagStr) Set(value string) error {
f.value = &value
return nil
}
func (f *flagStr) Get() *string {
return f.value
}
func (f *flagStr) String() string {
if f.value != nil {
return *f.value
}
return ""
}
var (
appFlags struct {
appID flagStr
appSecret flagStr
}
)
func main() {
flag.Var(&appFlags.appID, "FBAppID", "Facebook Application ID")
appFlags.appID.Set("1234567890")
flag.Var(&appFlags.appSecret, "FBAppSecret", "Facebook Application Secret")
flag.Parse()
fmt.Println(flag.Lookup("FBAppID")) // print the Flag struct
fmt.Println(&appFlags.appID)
}
Output :
&{FBAppID Facebook Application ID 1234567890 }
1234567890
Reference :
Advertisement
Something interesting
Tutorials
+10.6k Golang : Allow Cross-Origin Resource Sharing request
+12.5k Golang : Arithmetic operation with numerical slices or arrays example
+9k Golang : Populate or initialize struct with values example
+10.2k Golang : How to profile or log time spend on execution?
+6.6k Golang : Warp text string by number of characters or runes example
+6.9k Golang : Normalize email to prevent multiple signups example
+21.2k Golang : How to force compile or remove object files first before rebuild?
+14.5k Golang : How to determine if user agent is a mobile device example
+17.9k Golang : Login and logout a user after password verification and redirect example
+24.5k Golang : GORM read from database example
+8.8k Golang : Gorilla web tool kit schema example
+7.3k Golang : File system scanning