Skip to content

encoding/{protojson,prototext}: add MustUnmarshal function #1202

@dsnet

Description

@dsnet

I'm noticing that text serialization (and to some degree JSON) is used to quickly initialize a lot of data in tests (and sometimes in not-test code at init) with a pattern like:

const initData = `...` // text data
m := new(foopb.MyMessage)
if err := prototext.Unmarshal([]byte(initData), m); err != nil {
    panic(err)
}
return m

With the upcoming introduction of generics, perhaps we should add a helper for this:

func MustUnmarshal[M proto.Message](s string) M {
    var m M
    m = m.ProtoReflect().New().Interface()
    if err := Unmarshal([]byte(s), m); err != nil {
        panic(err)
    }
    return m
}

Thus, usage of this would be something like:

m := prototext.MustUnmarshal[*foopb.MyMessage](initData)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions