问题
Suppose I have defined a struct in an Apache Thrift IDL file which contains two fields. For example:
struct Thing {
1: optional string name,
2: optional i32 size
}
This means a client can supply a Thing object with no fields, a name, a size, or a name and a size. But what if I want a Thing object to have either a name or a size (exclusive or)? At the moment I have to use my implementation code to guard against a client supplying a Thing with no fields or both fields; and also document/comment how the client should specify a Thing object.
In short, if someone defines a struct containing various fields, is it possible to express in the IDL itself that you only want exactly one of those fields to be supplied in a client? (I'm using Apache Thrift 0.9.0.) It would be great if you could say something like the following (| = or):
struct Thing {
1: required (string name | i32 size)
}
回答1:
Use unions:
union Thing {
1: string name,
2: i32 size
}
Optional can be omitted, required is not allowed/useful with unions.
Unions have been introduced with 0.9.0 (IIRC) but 0.9.1 has improved support of them.
来源:https://stackoverflow.com/questions/18923120/how-do-you-say-in-a-thrift-idl-that-a-client-should-include-exactly-one-of-a-set