英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论