What Is Zero-Cost Abstraction in Rust?

Zero-cost abstractions in Rust mean high-level code compiles to machine code with the same performance as low-level code, adding no runtime overhead. The compiler achieves this by inlining generic code and removing unused abstractions during compilation, ensuring features like `impl` blocks and trai

What Is Zero-Cost Abstraction in Rust?

Zero-cost abstractions in Rust mean high-level code compiles to machine code with the same performance as low-level code, adding no runtime overhead. The compiler achieves this by inlining generic code and removing unused abstractions during compilation, ensuring features like impl blocks and traits cost nothing extra at runtime.

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn width(&self) -> bool {
        self.width > 0
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    if rect1.width() {
        println!("The rectangle has a nonzero width; it is {}", rect1.width);
    }
}

This method call compiles to the exact same assembly as writing self.width > 0 directly, proving the abstraction is free.