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
+9.9k Golang : Function wrapper that takes arguments and return result example
+13.7k Golang : Activate web camera and broadcast out base64 encoded images
+29.9k Golang : Get and Set User-Agent examples
+10.9k Golang : Get UDP client IP address and differentiate clients by port number
+39.1k Golang : How to iterate over a []string(array)
+7.9k Golang : Example of how to detect which type of script a word belongs to
+6.2k Linux/Unix : Commands that you need to be careful about
+26k Golang : How to read integer value from standard input ?
+6.3k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+16k Golang : Read large file with bufio.Scanner cause token too long error
+19.7k Golang : Set or Add HTTP Request Headers
+14.1k Golang : Reverse IP address for reverse DNS lookup example