This most likely stems from a misunderstanding of what interface{} is in go. I have the following code
type Configuration struct {
Username string
}
func loadJson(jsonStr []byte, x *Configuration}) {
json.Unmarshal(jsonStr, x)
}
func main() {
//var config *Configuration
config := new(Configuration)
file, e := ioutil.ReadFile("config.json")
loadJson(file, config)
fmt.Printf("%s
", config.Username)
}
It loads a json configuration into the config variable. I want to make the loadJson function more abstract and accept any struct. I thought the best way to do that would be to accept a *interface{}
, however I get the following error when changing the loadJson Signature.
./issue.go:30: cannot use config (type *Configuration) as type *interface {} in argument to loadJson:
*interface {} is pointer to interface, not interface
Instead load json should be this
func loadJson(jsonStr []byte, x interface{}}) {
json.Unmarshal(jsonStr, x)
}
Is interface{} already a pointer? Also the error message doesn't make the most sense to me, isn't configuration a pointer to an interface? Also, if I change json.Unmarshal(jsonStr, x)
to json.Unmarshal(jsonStr, &x)
it will work perfectly fine still. What is going on here that allows that to work?
Side question but relevant to pointers, why can't I declare a pointer like the commented out line(under main)?