proto UnmarshalText 在未知字段上失败

proto UnmarshalText fails on unknown field

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

例如,这个有效:

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

但这不是:

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

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

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

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