Oneof
Oneof becomes very handy in terms of space optimization when you have many optional fields in a message and know that at most only one will be set.
The implementation of Oneof shares the same memory space for all the fields, so it doesn’t need to reserve space for the other tags having empty fields.
Of course with the language implementation, you should have a WhichOneOf
method in order to determine what was the set value.
syntax
=
"proto2"
;
message
Film
{
message
Character
{
oneof
has
{
string
laser_gun_model
=
1
;
int32
laser_sword_power
=
2
;
}
}
}
In this example setting laser_gun_model
or laser_sword_power
allows you to know which type of weapon the Character
has. Looking into the value in the example provides you with additional information (gun model as a string, or laser power as an integer).