Losing mutability? Turning error[E0596] cannot borrow as mutable into error[E0308] mismatched types does not help
⚓ Rust 📅 2025-11-15 👤 surdeus 👁️ 6I've a shallow struct nesting with an inner and an outer. I implemented put-methods that shall modify the inner via the outer struct. Both methods take a mutable &self as first parameter. The outer does not compile and I got stuck with error[E0596]: cannot borrow **ias mutable, as it is behind a& reference
use std::collections::BTreeSet;
#[derive(Eq, Ord, PartialEq, PartialOrd)]
struct Inner { values: Vec<String> }
impl Inner {
fn new() -> Self { Self { values: Vec::new() } }
fn put(&mut self, val: &str) -> usize {
self.values.push(val.to_string());
self.values.len()
}
}
struct Outer { container: BTreeSet<Inner> }
impl Outer {
fn new() -> Self { Self { container: BTreeSet::new() } }
fn put(&mut self, val: &str) -> usize {
let i = &mut self.container.first().unwrap();
i.put(&val.to_string())
}
}
The retrieval of i is as explicit as this post suggests but that does not help.
Usually the compiler gives helpful hints but this time I am lost. Both methods get the underlying struct mutable. i is mutable and enclosed by an owned o so what is wrong here?
I can trade this error in for error[[E0308](https://doc.rust-lang.org/error_codes/E0308.html)]: mismatched types by making i's retrieval more explicit with let i: &mut Inner = self.container.first().unwrap(); but that doesn't help. I assume the expression &mut self.container.first().unwrap(); does not return a mutable owned Inner but that's what should happen.
What am I missing?
2 posts - 2 participants
🏷️ Rust_feed