Open ziranliu opened 5 years ago
+1, I would expect proto.Marshal to return an error in this case.
Likewise, this should be true:
var m *pb.MyMessage
_, err := proto.Marshal(m)
if err == nil {
t.Errorf("no error returned when proto.Marshal called with nil value")
}
After some further investigation, I think this is by design. It seems that protobuf uses some unsafe logic to achieve faster serialization times.
@prestonvanloon how much time not doing a nil check saves, compared to always protect against crashes?
Libraries should not panic the whole application when somethings go wrong, especially if it's API is returning an error.
I found proto.Marshal() would panic in the following case:
test.proto:
run:
test.go:
run:
Then it will panic("panic: runtime error: invalid memory address or nil pointer dereference") . While the code generated by standard protobuf will returns an error("proto: repeated field Foos has nil element").