I have 2 structs and one of them is made of protobuf, the other is made from xorm`s table struct.
There is a function which needs []*UserResult but I only have []*Users.
How do I transform them?
//user.proto =>
message UserResult {
int64 uid = 1 ;
string name = 2 ;
}
//user.go
type User struct {
uid int64
name string
}
func GetUserList(){
var users []*User
return xorm.xxxx.Get(&users)
}
// server.go
func (s *server)GetUserList() ([]*UserRequest , error) {
users := model.GetUsers()
// here how to make users ---> []*UserRequest ???
}
Use a for loop:
var userRequests []* UserRequest
users := model.GetUsers()
for _, u := range users {
ur := &UserRequest{name:u.Name, uid:u.uid, etc...}
userRequests = append(userRequests,ur)
}
You could use a function NewUserRequest(u) instead of constructing a ur inline like this. You haven't shown UserRequest so the fields would have to be adapted to whatever fields you have in there.
The generated from (user.proto
) should have JSON annotations on them. By adding JSON annotations to your type in user.go
you can marshal the User
and unmarshal it into a UserRequest
and vice-versa. Note that this approach is not very performant (it uses a lot of unnecessary cpu for marshaling JSON and creates a bit of garbage to collect), it is however easy to do for a type that has many fields or one that changes a lot.
Another approach would be to use reflection. This will allow you to convert between any two types with the same fields. Might be a little faster than JSON, but not as fast as function that converts between the two.