Lifetime issue in struct

āš“ Rust    šŸ“… 2025-07-30    šŸ‘¤ surdeus    šŸ‘ļø 11      

surdeus

Warning

This post was published 126 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Lifetime issue in struct
#[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

Read full topic

šŸ·ļø Rust_feed