#1415·protobuf

protoc-gen-go: oneof getters panic on typed-nil values.

Author: anzboiCreated Feb 17, 2022Updated Nov 11, 2025

What version of protobuf and what language are you using? Golang

bash
google.golang.org/protobuf v1.26.0

$ protoc --version
libprotoc 3.17.3

What did you do? Panic occurs when you set a typed nil on a oneof field

proto
// test.proto
message Test {
    oneof myOneof {
        string str = 1;
    }
}
go
// main.go
var typedNil *pb.Test_myOneof
t := &pb.Test{MyOneof: typedNil}
fmt.Println(t.GetStr())

What did you expect to see? Empty string

What did you see instead?

bash
panic: runtime error: invalid memory address or nil pointer dereference

Possibly related: #478

Anything else we should know about your project / environment?

I tracked down the source of the panic. The generated getter for the oneof field does a nil check on the interface value, but not the Str value after casting it. Following code was generated with the above tool versions.

go
func (x *Test) GetStr() string {
	if x, ok := x.GetMyOneof().(*Test_Str); ok {
		return x.Str
	}
	return ""
}

In the typed-nil case, the cast works and reports true, so the code attempts to access x.Str, but x is in fact nil. There should be an additional nil check on x.

I imagine this case is probably not intended to come about in practice, but it is certainly possible.