bhylu.com

Advertisements

Rust Methods and impl

Associate behaviour with the type that owns its invariant.

How it works

An impl block defines associated functions and methods. A method taking &self inspects an instance without moving it, while &mut self requests a mutable borrow. An associated constructor does not need a self parameter. Use these choices to express ownership and mutation at the call site rather than accepting broader access than the operation needs.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

methods.rs

fn main() {
    struct Tray { packets: u32 }
    impl Tray {
        fn new(packets: u32) -> Self { Self { packets } }
        fn packets(&self) -> u32 { self.packets }
    }
    let tray = Tray::new(8);
    assert_eq!(tray.packets(), 8);
    println!("Read-only method reports {} packets", tray.packets());
}

Expected result

Read-only method reports 8 packets

new returns an owned instance and packets reads through a shared borrow. Calling the method twice shows that it does not consume the tray. Constructors are a good place for validation, but the demonstration does not claim to enforce a range; later Result helpers show how to expose a fallible boundary.

Primary technical reference: Rust documentation.