Traits that differ only in mutability of self param?

โš“ Rust    ๐Ÿ“… 2026-02-14    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 2      

surdeus

I have two traits that differ only in the mutability of the self param. As a way to kind of โ€œmergeโ€ them, so that I can put either one in, say, a Vec<Box<dyn Foo>>, I wrote a blanket impl.

It runs, but this is not something Iโ€™ve done before. So I wanted to check - does this look okay? Or is there a better way?

pub trait Foo {
    fn bar(&mut self);
}
pub trait FooImmutable {
    fn bar(&self);
}

impl Foo for i32 {
    fn bar(&mut self) {
        println!("Foo::bar for i32");
    }
}
impl FooImmutable for f32 {
    fn bar(&self) {
        println!("FooImmutable::bar for f32");
    }
}
impl<T: FooImmutable> Foo for T {
    fn bar(&mut self) {
        println!("Blacket impl");
        FooImmutable::bar(self);
    }
}
fn main() {
    let i: i32 = 123;
    let f: f32 = 1.2;
    let mut foos: Vec<Box<dyn Foo>> = vec![];
    foos.push(Box::new(i));
    foos.push(Box::new(f));
    for foo in &mut foos {
        foo.bar();
    }
}

1 post - 1 participant

Read full topic

๐Ÿท๏ธ Rust_feed