Is this "reborrowing"? How to transform this struct?
⚓ Rust 📅 2026-02-08 👤 surdeus 👁️ 10I’ve got a LayoutCtx that wraps a &mut reference. I’m passing this down a tree of “widgets” as they do layout. But I’ve hit an bit of ugliness in my design, and feel I need to cheat a bit and create an OtherCtx from a LayoutCtx, just for a few lines of code.
This looks like what people are calling a “reborrow”, but I’m not sure.
The compile error is show below. Is there any way to do this? Maybe I need to pass my LayoutCtx by value, not by &mut reference. That would mean I have to keep reconstructing them, which is annoying.
struct State { }
struct LayoutCtx<'s> {
window_state: &'s mut State
}
struct OtherCtx<'s> {
window_state: &'s mut State
}
impl<'s> LayoutCtx<'s> {
fn fee(&self) { }
fn to_other_ctx(&mut self) -> OtherCtx<'s> {
// fn to_other_ctx(mut self) -> OtherCtx<'s> {
OtherCtx {
window_state: self.window_state
}
}
}
impl<'s> OtherCtx<'s> {
fn faa(&self) { }
}
fn layout(lo_ctx: &mut LayoutCtx) {
// But I need OtherCtx, just for a bit!
let mut other_ctx = lo_ctx.to_other_ctx();
other_ctx.faa();
lo_ctx.fee();
}
fn main() {
println!("Test");
let mut state = State { };
let mut lo_ctx = LayoutCtx { window_state: &mut state };
layout(&mut lo_ctx);
}
Compile error:
error: lifetime may not live long enough
--> learning/rust_lang/examples/transform_ctxs.rs:13:9
|
9 | impl<'s> LayoutCtx<'s> {
| -- lifetime `'s` defined here
10 | fn fee(&self) { }
11 | fn to_other_ctx(&mut self) -> OtherCtx<'s> {
| - let's call the lifetime of this reference `'1`
13 | / OtherCtx {
14 | | window_state: self.window_state
15 | | }
| |_________^ method was supposed to return data with lifetime `'s` but it is returning data with lifetime `'1`
2 posts - 2 participants
🏷️ Rust_feed