How to Use the Handle-Body (Pimpl) Pattern in Rust

Implement the Handle-Body pattern in Rust by wrapping private implementation details in a Box within a public struct to hide fields and ensure binary compatibility.

Use the Handle-Body pattern (Pimpl) in Rust by defining a public struct that holds a Box to a private inner struct containing the implementation details. This hides the internal fields from the public API, allowing you to change the implementation without breaking binary compatibility for users of your library.

// lib.rs
use std::fmt::Debug;

// The public handle
pub struct MyStruct {
    inner: Box<MyStructImpl>,
}

// The private body (implementation details)
struct MyStructImpl {
    secret_data: String,
    count: i32,
}

impl MyStruct {
    pub fn new() -> Self {
        MyStruct {
            inner: Box::new(MyStructImpl {
                secret_data: String::from("hidden"),
                count: 0,
            }),
        }
    }

    pub fn get_count(&self) -> i32 {
        self.inner.count
    }

    pub fn increment(&mut self) {
        self.inner.count += 1;
    }
}

impl Debug for MyStruct {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MyStruct {{ count: {} }}", self.inner.count)
    }
}