Golang how to return list in gRPC

Viewed 72

I have two structures. One own, and the other generated through gRPC. The problem is that when you try to return your own through gRPC, an error is generated: "cannot use list (variable of type []db.User) as *pb.UsersList value in return statement" How can I convert [db.User in *pb.UserList? []User

type User struct{
    Username string `json:"username"`
    Password string `json:"password"`
}

gRPC UsersList:

type UsersList struct {
    state protoiml.MessageState
    sizeCache protoiml.SizeCache
    unknownFields protoiml.UnknownFields
    User []*User `protobuf:"bytes,1,rep,name=user,proto3" json:"user,omitempty
}
1 Answers

[]db.User and *pb.UsersList are different types and you cannot just return one as the other (for a start one is a slice the other a pointer to a struct). You will need to convert with something like this (playground):

func convert(in []User) *PbUsersList {
    pbU := make([]*PbUser, len(in))
    for i := range in {
        pbU[i] = &PbUser{User: in[i].Username, Pass: in[i].Password}
    }
    return &PbUsersList{User: pbU}
}

Note: To demonstrate this I have put both structures in main in your real code []User would be []db.User and *PbUsersList would be *UsersList.

Related