Why does this borrow last for whole statement?

⚓ Rust    📅 2026-02-11    👤 surdeus    👁️ 1      

surdeus

I have a line like this:

vstack.add(ctx, self.voice_control(ctx));
// error: cannot borrow `*ctx` as mutable more than once at a time

It’s building some UI widgets. The ctx is &mut WindowCtx. It doesn’t compile, and I understand the error message. But … why? In this case voice_control builds a widget and returns Rc<dyn Widget>. It has no lifetime parameter, so shouldn’t it be able to see that the borrow is done once the argument expression (self.voice_control(ctx)) has been evaluated? It seems like it should be able to compile that one line, as if I’d written:

let temp = self.voice_control(ctx);
vstack.add(ctx, temp);

which does compile.

4 posts - 4 participants

Read full topic

🏷️ Rust_feed