or-type
ftd
supports or-type
, which is loosely equivalent of enum
in Rust, and is otherwise known as “algebraic data type”.
Declaring an or-type
Say we have a sales business and we are going to get “leads”, and a lead can be either an individual or a company. In case of individuals we have fields like their name, and phone number. For a company we have company name and the name of contact and the fax number of the company.
An or-type
can be created like this:
-- or-type lead: \--- individual: name: caption phone: string \--- company: name: caption contact: string fax: string
Here we have used ftd::p1
’s “sub-section” to represent each possibilities.
The declarations individual
or company
, are called or-type
variants, and they use similar syntax as record
declarations.
or-type
variables
A variable can be created like this:
-- var amitu: Amit Upadhyay type: lead.individual phone: 1231231231 -- var acme: Acme Inc. type: lead.company contact: John Doe fax: +1-234-567890
Note that in the type
we have included the or-type
as well as the exact variant
we want to construct.
Reading An or-type
From Rust
An or-type
in ftd
is equivalent of a enum
in Rust.
Rust Type
To read the above ftd
file from Rust we have to first create an enum
in Rust that is compatible with our lead
definition:
#[allow(non_camel_case_types)] #[derive(serde::Deserialize)] #[serde(tag = "type")] enum Lead { individual { name: String, phone: String }, company { name: String, contact: String, fax: String }, }
For each variant in lead
or-type
, we have a corresponding clause in Lead
enum
.
Note: We have to match the case of enum variant with the one used in ftd
, ftd
has a naming convention with lower case, where as Rust prefers CamelCase, so we have used #[allow(non_camel_case_types)]
.
Note: Each enum
must have #[serde(tag = "type")]
as this is how we track which variant is represented in data.
Getting Data From FTD File
Once the mapping is in place, we can use the ftd
crate to parse an ftd
file, and get data out of it:
let doc = ftd::p2::Document::from("some/id", source, lib)?; let amitu: Lead = doc.get("amitu")?;
You can read more details of reading ftd
files “Reading FTD Files” guide.