1

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.

Arka Wbija
  • 11
  • 2
  • Is https://stackoverflow.com/a/59568458/4690866 what you are looking for? Seems like Any or oneof is what you'd be looking for here. – Eric Anderson Jan 03 '23 at 17:39

1 Answers1

2

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.

DazWilkin
  • 32,823
  • 5
  • 47
  • 88