Reputation: 11
is it possible to create a field that can hold different types of messages? Let's say I wanted to send a request to create a car, but it can have different types of windows in it, and each type requires different fields to be present:
message TintedWindows {
double tintPercent = 1;
string tintColor = 2;
}
message ArmoredWindows {
string armorClass = 1;
}
message CreateCarRequest {
string color = 1;
int wheels = 2;
int doors = 3;
Windows??? windows = 4;
}
Is there a way of doing that smoothly or I have to add all those messages and check which one is empty and which one is not:
message CreateCarRequest {
string color = 1;
int wheels = 2;
int doors = 3;
TintedWindows tinted = 4;
ArmoredWindows armored = 5;
}
then do: (pseudocode)
windowsInterface windows;
if req.tinted != null && req.armored == null {
windows = newTinted(req.tinted)
} else if req.tinted == null && req.armored != null {
windows = newArmored(req.armored)
} else {
throw error
}
I'm curently doing that using the second method and it's a bit cumbersome.
Upvotes: 1
Views: 596
Reputation: 40336
You can use Oneof
.
message CreateCarRequest {
string color = 1;
uint32 wheels = 2;
uint32 doors = 3;
oneof windows {
TintedWindows tinted = 4;
ArmoredWindows armored = 5;
}
}
There is no int
type (see scalar), you'll need to choose one of the available types, probably uint32
for number of wheels
and doors
.
Upvotes: 2