Traits that differ only in mutability of self param?
โ Rust ๐ 2026-02-14 ๐ค surdeus ๐๏ธ 2I 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
๐ท๏ธ Rust_feed