SoFunction
Updated on 2025-03-02

A pitfall that may be encountered when loading json in go language

Problem introduction

Go is a simple but profound language. Everyone knows that the Go language standard library has built-in processing of json files, which is very convenient. Recently, when writing an application, you need to load configuration from the json file. Since you are a novice in go, you ignore a detail, resulting in the loading content always being empty. I won’t say much below. Friends who need it, let’s take a look at the detailed introduction:

Code Demo

The code is the best description vector

package config

type config struct{
 a string `json:"a"`
 b string `json:"a"`
}
func Load(file string)(*config, error){
 c = &config{}
 file, err := (file)
 if err != nil {
 //file open failed todo 
 }
 jsonParser := (file)
 err = (c)
 //What is the value of c}

in conclusion

After seeing the above code, do you think that c has been assigned successfully?

In fact, it failed, the json file parsing succeeded but the final assignment failed

The reason is actually very simple:

go Variables in different packages Functions Method access, the one that distinguishes access permissions is Variable Function Whether the first letter of the method is capitalized. If it is capitalized, it can be accessed in other packages.

In this question, the json package and config are not the same package, and the access failed and cannot be set

a b must be rewritten to capital to assign value

think

The reason why filed in config is set to lowercase is to do access control. If you insist on lowercase, how can you assign a value to the field of config? Friends who know can leave a message to share~

Okay, the above is the entire content of this article. I hope the content of this article will be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.