How do you say in a Thrift IDL that a client should include exactly one of a set of fields in a struct?

戏子无情 提交于 2019-12-21 16:51:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!