英文:
Golang how to return list in gRPC
问题
我有两个结构体。一个是自己定义的,另一个是通过gRPC生成的。问题是,当尝试通过gRPC返回自己定义的结构体时,会生成一个错误:"无法将列表(类型为[]db.User)作为pb.UsersList值在返回语句中使用"。我该如何将[db.User]转换为pb.UserList?
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
type UsersList struct {
state protoiml.MessageState
sizeCache protoiml.SizeCache
unknownFields protoiml.UnknownFields
User []*User `protobuf:"bytes,1,rep,name=user,proto3" json:"user,omitempty"`
}
你可以使用以下代码将[db.User]转换为*pb.UserList:
func ConvertToPBUserList(users []db.User) *pb.UsersList {
userList := &pb.UsersList{}
for _, user := range users {
pbUser := &pb.User{
Username: user.Username,
Password: user.Password,
}
userList.User = append(userList.User, pbUser)
}
return userList
}
这个函数将接受一个[db.User]类型的用户列表,并将其转换为pb.UserList类型。它会遍历每个用户,并将其转换为pb.User类型,然后将其添加到pb.UserList的User字段中。最后,它将返回转换后的pb.UserList对象。
英文:
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
得分: 1
[]db.User
和*pb.UsersList
是不同的类型,你不能简单地将一个返回为另一个(首先,一个是切片,另一个是指向结构体的指针)。你需要使用类似下面这样的方法进行转换(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}
}
注意:为了演示,我将这两个结构体放在了main
函数中,而在你的真实代码中,[]User
应该是[]db.User
,*PbUsersList
应该是*UsersList
。
英文:
[]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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论