9

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)
}
snark
  • 2,462
  • 3
  • 32
  • 63

1 Answers1

16

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.

JensG
  • 13,148
  • 4
  • 45
  • 55
  • 1
    Ok, thanks, I wasn't aware of unions in Thrift. They look useful. If I may ask 3 follow-up questions please: 1) If I used a union would a Thrift service automatically throw an exception if it received a Thing without either its name or size fields set? 2) Which languages support 'union' in Thrift 0.9.1? I'm using Java, C# and Python so all three would need to work with the union type. 3) Are there any restrictions on the use of 'union'? What I really want to do is define a struct, one of whose fields will be a type which is a union of an enum and another struct type. I hope that makes sense! – snark Sep 23 '13 at 12:32
  • (1) Good question. Without looking into the source, IIRC Java complains, but the other languages do not. So you ought to check that on your own. – JensG Sep 23 '13 at 19:56
  • (3) You define Union just like a struct. in fact, those languages who do not Support unions natively will generate code for a struct. – JensG Sep 23 '13 at 19:59
  • (2) More or less all. Some natively, some via struct. – JensG Sep 23 '13 at 20:00
  • OK thanks very much @JensG. Shame about (1) because avoiding have to write such guard code was part of the appeal. However I'm definitely still tempted to try using unions. At least the union type expresses what I want semantically in the IDL itself. – snark Sep 24 '13 at 10:57