在进行struct变量转码时,发现不管我传入的是什么值,最后传回的都是{}
于是写了一个测试代码,如下进行验证。
package main
import (
"encoding/json"
"fmt"
)
type test struct {
institutionID string `json:"institution_id"`
userID string `json:"user_id"`
dateTime string `json:"date_time"`
type1 string `json:"type"`
sum string `json:"sum"`// negative for withdraw, positive for top
}
func main() {
var args = []string{"12","23","34","45","56"}
var h = test{institutionID:args[0],userID:args[1],dateTime:args[2],type:args[3],sum:args[4]}
hAsBytes,_ := json.Marshal(h)
fmt.Print(hAsBytes)
}
得到的还是{}
然后断点调试了一下,发现h
中的值根本没有传入到json.Marshal
中进行转码。
原来golang对变量是否包外可访问,是通过变量名的首字母是否大小写来决定的,所以只要我们把struct中的变量名改为大写即可。
更改后代码如下
package main
import (
"encoding/json"
"fmt"
)
type test struct {
InstitutionID string `json:"institution_id"`
UserID string `json:"user_id"`
DateTime string `json:"date_time"`
Type string `json:"type"`
Sum string `json:"sum"`// negative for withdraw, positive for top
}
func main() {
var args = []string{"12","23","34","45","56"}
var h = test{InstitutionID:args[0],UserID:args[1],DateTime:args[2],Type:args[3],Sum:args[4]}
hAsBytes,_ := json.Marshal(h)
fmt.Print(hAsBytes)
}
这样我们就得到了正确的转码值