proto.UnmarshalText在未知字段上失败

huangapple go评论79阅读模式
英文:

proto UnmarshalText fails on unknown field

问题

在Golang中,当文本包含未知字段时,UnmarshalText会失败。

例如,以下代码可以正常工作:

rawstr := "knownfield1:\"abc\" knownfield2:\"def\""
var msg pb.MyProtoMessage
err := proto.UnmarshalText(rawstr, &msg)
// 没有错误

但是以下代码会失败:

rawstr := "knownfield1:\"abc\" knownfield2:\"def\" UNKNOWNfield:\"xyz\""
var msg pb.MyProtoMessage
err := proto.UnmarshalText(rawstr, &msg)
// 错误

有没有人知道如何让UnmarshalText忽略未知字段?

英文:

In golang UnmarshalText fails when the text contains unknown field.

For example, this works:

rawstr := "knownfield1:\"abc\" knownfield2:\"def\""
var msg pb.MyProtoMessage
err := proto.UnmarshalText(rawstr, &msg)
// no error

But this doesn't:

rawstr := "knownfield1:\"abc\" knownfield2:\"def\" UNKNOWNfield:\"xyz\""
var msg pb.MyProtoMessage
err := proto.UnmarshalText(rawstr, &msg)
// error

Does anyone know how to get UnmarshalText to ignore unknown fields?

答案1

得分: 3

你应该在UnmarshalOptions上设置DiscardUnknown,以忽略未知字段:

rawstr := "knownfield1:\"abc\" knownfield2:\"def\" UNKNOWNfield:\"xyz\""
var msg pb.MyProtoMessage
unmarshaler := prototext.UnmarshalOptions{DiscardUnknown: true}
err := unmarshaler.UnmarshalText(rawstr, &msg)
英文:

You should set DiscardUnknown on UnmarshalOptions to ignore unknown fields:

rawstr := "knownfield1:\"abc\" knownfield2:\"def\" UNKNOWNfield:\"xyz\""
var msg pb.MyProtoMessage
unmarshaler := prototext.UnmarshalOptions{DiscardUnknown: true}
err := unmarshaler.UnmarshalText(rawstr, &msg)

huangapple
  • 本文由 发表于 2021年5月26日 08:42:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/67697199.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定