Installing Snapfit and your first singleton
Time to write a container of our own. We'll start as small as possible: one component, the shop's configuration, built once and shared by everyone who asks for it.
Adding Snapfit
snapfit is one crate. Add snapfit = "0.1.0" under [dependencies] in your Cargo.toml. It gives you the #[container] attribute and the Container trait. You need Rust 1.85.0 or newer; your own crate can use any edition from 2018 on.
A configuration to share
Here is the shop's configuration. It is an ordinary struct with an ordinary new():
#[derive(Default)]
pub struct ShopConfig {
pub store_name: &'static str,
}
impl ShopConfig {
pub fn new() -> Self {
Self {
store_name: "Northwind Books",
}
}
}Now the container. We mark the struct with #[container], and the config field with #[singleton]. A singleton is a component the container builds once and then shares:
#[container]
pub struct ShopContainer {
#[singleton]
config: Arc<ShopConfig>,
}Let's build the container, ask for the configuration twice, and check whether we got the same one both times:
fn main() {
let container = ShopContainer::new();
let first = container.get_config();
let second = container.get_config();
println!("store: {}", first.store_name);
println!("same allocation: {}", Arc::ptr_eq(&first, &second));
}It prints:
store: Northwind Books
same allocation: trueThe same allocation, both times. Think of the one printer in an office: everyone sends their pages to it, and nobody buys a printer of their own.
What happened behind the scenes
#[container] wrote three things for us.
- A way to build the container. It generated
ShopContainer::new(), and also implementedDefaultandsnapfit::Container, soShopContainer::default()builds it too. - The
Arcaround the configuration. The field's type isArc<ShopConfig>, so the container calledShopConfig::new()and wrapped the plainShopConfigit returned inArc::new(...)itself. Your constructor returns the plain type; theArcis the container's job. - A getter. For each field, it generated a method named after it, here
get_config(), which returns a clone of the field. Cloning anArconly adds one to a counter, so both calls point to the sameShopConfig, which is whatArc::ptr_eqconfirmed.
Which problem this solves
- Duplicated resources (Chapter 1):
configis built once, when the container is built, and every call toget_config()returns that same one, asArc::ptr_eqshows. - Sharing by convention (Chapter 3): every field of a container is built once and shared. There is no second kind of field that is quietly built again on each call, so there is nothing to remember.
Remember
snapfitneeds Rust1.85.0or newer, and your crate can use any edition from 2018 on.- A
#[singleton]field with nodepsneeds nothing, soShopContainer::new()builds it when it reaches the field, or earlier if a field declared before it needs it. - For an
Arc<T>field, your constructor returnsT, andsnapfitwraps it inArc::new(...)for you.