Lifetime issue in struct
ā Rust š 2025-07-30 š¤ surdeus šļø 11#[derive(Debug)]
struct NumRef<'a> {
x: &'a i32,
}
#[derive(Debug)]
struct NumRefMut<'a> {
x: &'a mut i32,
}
impl<'a> NumRef<'a> {
fn as_i32_ref(&'a self) -> &'a i32 {
self.x
}
}
impl<'a> NumRefMut<'a> {
fn as_i32_ref(&'a mut self) -> &'a mut i32 {
self.x
}
}
fn main() {
let mut x: i32 = 99;
let mut y: i32 = 99;
let mut x_num_ref = NumRef { x: &x };
let mut y_num_ref = NumRefMut { x: &mut y };
let x_i32_ref = x_num_ref.as_i32_ref();
let y_i32_ref = y_num_ref.as_i32_ref();
let _ = &mut x_num_ref; //L1
// let _ = &y_num_ref; //L2
}
Iām a rust beginner, this code succeeds to compile. If uncomment line L2, there is an error , because y_i32_ref continues to mutable borrow y_num_ref even if y_i32_ref is not used . But line L1 has no problem? I think x_i32_ref should borrow x_num_ref as y_i32_ref. Could anyone explain
1 post - 1 participant
š·ļø Rust_feed