Golang : does not implement flag.Value (missing Set method)
Keep getting this error message : does not implement flag.Value (missing Set method) while trying to write example for flag.Var() function today. Apparently, to assign value with flag.Var() function to a variable in a struct. You need to implement Set() and Get() method. It is helpful to have String() method as well.
To fix this error, all you need to do is the add the Set method.
For example :
package main
import (
"flag"
"fmt"
)
type flagStr struct {
value *string
}
// compiler will throw out missing Set method
// if this method below is ... well.. missing
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)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+15.1k Golang : Validate hostname
+5.6k nginx : force all pages to be SSL
+4.3k Linux : sudo yum updates not working
+20.3k Golang : Convert date string to variants of time.Time type examples
+5.1k Golang : Display advertisement images or strings on random order
+6.7k Golang : Squaring elements in array
+28.8k Golang : Save map/struct to JSON or XML file
+12k Golang : Extract part of string with regular expression
+6.3k Golang : Warp text string by number of characters or runes example
+26.3k Golang : Find files by extension
+10.1k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+11.1k Golang : Simple file scaning and remove virus example