The First Steps
As with any other crate, begin by adding fieldx
to your Cargo.toml
file:
[dependencies]
fieldx = { version = "0.2", features = ["sync"] }
A detailed list of crate feature flags is available in the FieldX documentation.
Next, annotate a struct with the #[fxstruct]
macro:
use fieldx::fxstruct;
#[fxstruct]
struct Book {
#[fieldx(get, set)]
title: String,
}
That's it! Now you can use it as follows:
let mut my_struct = Book::new();
my_struct.set_title("The Hitchhiker's Guide To The Galaxy".to_string());
assert_eq!(my_struct.title(), "The Hitchhiker's Guide To The Galaxy");
Let's say the struct grows in size and complexity, and it's time to implement the builder pattern. No problem! Simply add the builder
attribute to the struct:
use fieldx::fxstruct;
#[fxstruct(builder, get)]
struct Book {
title: String,
author: String,
#[fieldx(get(copy))]
year: u32,
// How many books are available in the depository.
#[fieldx(get(copy), builder(off))]
available: u32,
}
let my_struct = Book::builder()
.title("The Hitchhiker's Guide to the Galaxy".to_string())
.author("Douglas Adams".to_string())
.year(1979)
.build()
.expect("Failed to build Book object");
assert_eq!(my_struct.title(), "The Hitchhiker's Guide to the Galaxy");
assert_eq!(my_struct.author(), "Douglas Adams");
assert_eq!(my_struct.year(), 1979);
assert_eq!(my_struct.available(), 0);