当前位置: > > > > 如何用数据动态填充结构体?
来源:stackoverflow
2024-04-28 13:30:31
0浏览
收藏
来到的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《如何用数据动态填充结构体?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!
问题内容
在我用 golang 编写的 grpc 服务中,我有这样的 rpc 方法
,名为 createcity
。正如您所看到的,在这个方法中,我想在数据库中创建一条新记录,并返回有关该记录的所有信息作为响应。
func (server *server) createcity(context context.context, request *proto.createcityrequest) (*proto.createcityresponse, error) { city := proto.city { name: request.getcity().name, country: request.getcity().country, } err := databases.dbgorm.table("city").create(&city).error if err != nil { utils.logger().println(err.error()) return nil, status.errorf(codes.internal, err.error()) } result := &proto.createcityresponse { city: &city, } return result, nil }
proto 文件如下所示:
syntax = "proto3"; package proto; import "google/protobuf/wrappers.proto"; import "google/protobuf/timestamp.proto"; import "github.com/gogo/protobuf/gogoproto/gogo.proto"; option go_package = "./proto"; service cityservice { rpc createcity(createcityrequest) returns (createcityresponse) {} } message city { google.protobuf.stringvalue name = 1 [json_name = "name", (gogoproto.jsontag) = "name", (gogoproto.wktpointer) = true]; google.protobuf.stringvalue country = 2 [json_name = "country", (gogoproto.jsontag) = "country", (gogoproto.wktpointer) = true]; } message createdealergrouprequest { city city = 1; } message createdealergroupresponse { city city = 1; }
是否可以在不显式指定名称的情况下动态填充数据结构?正如您现在所看到的,我明确指定了字段的名称及其值:
city := proto.City { Name: request.GetCity().Name, Country: request.GetCity().Country, }
解决方案
您可以使用 json.marshal
创建 json 字节数组,然后使用 json.unmarshal
inrec, _ := json.Marshal(request.GetCity()) json.Unmarshal(inrec, &city)
理论要掌握,实操不能落!以上关于《如何用数据动态填充结构体?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注公众号吧!