Struct Methods With Impl Blocks
Attach constructors and queries to a struct through impl blocks, keeping associated functions and &self borrows idiomatic.
Code
#[derive(Debug)]
struct Invoice {
number: u32,
cents: i64,
paid: bool,
}
impl Invoice {
// 关联函数:构造器惯例命名为 new
fn new(number: u32, cents: i64) -> Self {
Self { number, cents, paid: false }
}
// &self 借读:不取得所有权
fn total_cents(&self) -> i64 {
self.cents
}
// &mut self 借写:就地变更
fn mark_paid(&mut self) {
self.paid = true;
}
}
fn main() {
let mut invoice = Invoice::new(1001, 4_950);
invoice.mark_paid();
println!(
"invoice {} total {} paid {}",
invoice.number,
invoice.total_cents(),
invoice.paid
);
println!("{:?}", invoice);
}What the code does
The snippet is organized around the functions new, total_cents, mark_paid and main.
Applying it
The primary signature is fn new(number: u32, cents: i64) -> Self
Running the file prints labeled results such as invoice — each operation’s effect is visible in the output.
Start the program and main runs new, mark_paid and total_cents one after another.
Statements that matter
fn new(number: u32, cents: i64) -> Self {
Self { number, cents, paid: false }
}
fn total_cents(&self) -> i64 {
self.cents
}
fn mark_paid(&mut self) {
self.paid = true;
}
Interactive Tools for This Topic
FAQ
- What does Struct Methods With Impl Blocks print when run?
- Running the file directly is enough — expect labeled output lines such as `invoice`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.