结构体中有sync.Mutex如何构建此结构体并返回?
使用proto生成的对象,想初始化对象并返回,发现提示
Return copies the lock value: type 'userpb.UserInfoResponse' contains 'protoimpl.MessageState' contains 'sync.Mutex' which is 'sync.Locker'
这是我的代码:
func ModelToResponse(user model.User) userpb.UserInfoResponse {
userInfoRsp := userpb.UserInfoResponse{
Id: user.ID,
Password: user.Password,
Mobile: user.Mobile,
Nickname: user.NickName,
Gender: user.Gender,
Role: int32(user.Role),
}
if user.Birthday != nil {
userInfoRsp.Birthday = uint64(user.Birthday.Unix())
}
return userInfoRsp
}
一层层的查看源代码,发现确实有个sync.Mutex,网上翻阅了资料,大概意思就是不能复制,目前函数使用没有问题,但总感觉是个雷,求正确姿势。
为什么不
Marshal
后直接返回[]byte
?像这样:
我的理解是proto是本机格式(这里的model.User)和字节流的转换关系,proto结构体本身不需要也不应当在函数间传递,只需要在消息传输的时候进行转换。
函数间传递应该使用本机格式,应用间传递应该使用字节流