One idea
A trait is a shared promise. It says: any type that implements me will provide these methods.
Use traits when your CLI has different things that should behave in the same way.
Why traits matter
Your Rust CLI will grow. Today it may print one kind of report. Tomorrow it may print tasks, expenses, marks, links, or UPI splits.
Instead of writing separate print logic everywhere, define the behaviour once as a trait. Then each type decides how it does that behaviour.
Trait example
Here is a small CLI-style example. It has two different types, but both can be shown as a user-facing line.
trait Summary {
fn summary(&self) -> String;
}
struct Task {
title: String,
done: bool,
}
struct Expense {
label: String,
amount: u32,
}
impl Summary for Task {
fn summary(&self) -> String {
match self.done {
true => format!("[done] {}", self.title),
false => format!("[todo] {}", self.title),
}
}
}
impl Summary for Expense {
fn summary(&self) -> String {
format!("{}: ₹{}", self.label, self.amount)
}
}
fn print_summary(item: &impl Summary) {
println!("{}", item.summary());
}
fn main() {
let task = Task {
title: String::from("Submit HackIndia repo"),
done: false,
};
let expense = Expense {
label: String::from("Canteen chai"),
amount: 15,
};
print_summary(&task);
print_summary(&expense);
}Read the shape
trait Summary defines the method name. impl Summary for Task gives Task its version. impl Summary for Expense gives Expense its version.
print_summary takes &impl Summary. That means it accepts any value that implements Summary. It does not need to know whether the value is a Task or an Expense.
Common mistake
Do not put data fields inside a trait. A trait is not a struct.
Keep data in structs. Keep shared behaviour in traits. Then connect them with impl TraitName for StructName.
Use AI carefully
You can ask an AI tool: “Suggest one useful Rust trait for my CLI project and show how two structs can implement it.”
Check that the generated code has trait, struct, impl Trait for Struct, and a function that accepts &impl Trait or a generic trait bound. Also check it still compiles with cargo run.
When to add one
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done