结构体中有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,网上翻阅了资料,大概意思就是不能复制,目前函数使用没有问题,但总感觉是个雷,求正确姿势。

讨论数量: 3

为什么不Marshal后直接返回[]byte

像这样:

func ModelToResponse(user model.User) []byte {
    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())
    }

    b, err := proto.Marshal(userInfoRsp)
    if err != nil {
        panic(err)
    }
    return b
}

我的理解是proto是本机格式(这里的model.User)和字节流的转换关系,proto结构体本身不需要也不应当在函数间传递,只需要在消息传输的时候进行转换。
函数间传递应该使用本机格式,应用间传递应该使用字节流

2年前 评论
meitian (楼主) 2年前
renxiaotu (作者) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!