About go language loading json may encounter a pit
- 2020-06-03 06:54:02
- OfStack
It is
Go language is a simple but contains the meaning of language, everyone know go language summary in the standard library with built-in to json file processing, very convenient, when writing an application recently, need to load the configuration from json file, since it is go novice, ignore a detail, lead to load the content is empty all the time, the following few words said, need friends 1 up to look at the details:
Code demo
Code is the best vehicle for explanation
package config
type config struct{
a string `json:"a"`
b string `json:"a"`
}
func Load(file string)(*config, error){
c = &config{}
file, err := os.Open(file)
if err != nil {
//file open failed todo
}
jsonParser := json.NewDecoder(file)
err = jsonParser.Decode(c)
//c What is the value of theta
}
conclusion
If you look at the code above, do you think that c was assigned successfully?
In fact, no, the json file parsed successfully but ultimately failed to assign
The reason is simple:
go variable function method access in different packages, the difference between access rights is whether the variable function method is capitalized if it is capitalized, it can be accessed in other packages
In this case, the json package and config are not the same package, access failed and set cannot be accessed
a b must be written in uppercase to be assigned
thinking
The reason why filed in config is set to lower case is to do access control, if you stick to lower case, how to assign value to field of config? Know friends can leave a message to share oh ~