Practical Crates
Feature Toggle
Select an Output Shape
Crates often expose feature flags that choose one behavior while keeping the public call site small.
Program
Play the program to choose a JSON-shaped output or a compact text output.
feature_toggle.rs
fn main() {
let json_output = ;
let summary = build_summary("search", 3, json_output);
println!("{summary}");
}
fn build_summary(name: &str, count: i32, json_output: bool) -> String {
if json_output {
format!("{{\"name\":\"{name}\",\"count\":{count}}}")
} else {
format!("{name}:{count}")
}
}
fn main() {
let json_output = ;
let summary = build_summary("search", 3, json_output);
println!("{summary}");
}
fn build_summary(name: &str, count: i32, json_output: bool) -> String {
if json_output {
format!("{{\"name\":\"{name}\",\"count\":{count}}}")
} else {
format!("{name}:{count}")
}
}
feature flag
`json_output` stands in for a crate feature that selects one output strategy.
branch
Only one formatting branch runs for a chosen feature shape.
API boundary
`build_summary` hides the formatting choice behind one small function.