我是Go的新手.我已经读过Go中的封装是在包级别上.我有一个简单的Web控制器用例.我有一个结构作为一个JSON对象进入,并解组为结构类型.
type User struct{
Name String `json:"name"`
//Other Variables
}
Run Code Online (Sandbox Code Playgroud)
现在可以通过json.Unmarshal([] byte)将json解组为User Struct类型.但是,此User结构也可用于其他包.如何确保其他软件包只能访问与User相关的方法.
我能想到的一个解决方案:
type User struct{
name String
}
type UserJSON struct{
Name String `json:"name"`
}
func DecodeJSONToUser(rawJSON []byte) (User,error) {
var userJSON UserJSON
err := json.Unmarshal(rawJSON,&userJSON)
//Do error handling
return User{name:userJSON.Name},nil
}
Run Code Online (Sandbox Code Playgroud)
有没有一种可以实现这一目标的方法?