keyword

Rust impl: attach behavior to a type

An `impl` block defines methods and associated functions for a type, or implements a trait for a type. An inherent implementation is attached directly to the type. Expected output (not executed): 12 Why: The method reads both fields of the value. Common mistake: An impl block is not a place to declare additional instance fields.

Formal Syntax & Structure

rust syntaxrust
impl Type { fn method(&self) {} }

Working Example

Example Snippetrust
struct BoxSize { width: u32, height: u32 }impl BoxSize {    fn area(&self) -> u32 { self.width * self.height }}
fn main() {    let size = BoxSize { width: 4, height: 3 };    println!("{}", size.area());}
Rust Reference