Subtle borrowing behavior example

⚓ rust    📅 2025-06-04    👤 surdeus    👁️ 1      

surdeus

All of these functions fail to compile. However, they fail to compile for different reasons! Can you correctly identify why each example is an error?

Composed with Rust 1.87 edition 2024. [playground]

pub fn f1<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = x;
    *x;
    out
}

pub fn f2<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = &mut *x;
    *x;
    out
}
Answer / explanation (click for more details)
pub fn f3<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = std::convert::identity(x);
    *x;
    out
}

pub fn f4<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = std::convert::identity::<&mut _>(x);
    *x;
    out
}
Answer / explanation (click for more details)
pub fn f5<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = x as _;
    *x;
    out
}
Answer / explanation (click for more details)
pub fn f6<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out: &mut _ = x;
    *x;
    out
}
Answer / explanation (click for more details)
pub fn f7<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = &mut *{ x };
    *x;
    out
}

pub fn f8<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out = { x } as _;
    *x;
    out
}

pub fn f9<'a>(x: &'a mut i32) -> &'a mut i32 {
    let out: &mut _ = { x };
    *x;
    out
}
Answer / explanation (click for more details)

2 posts - 1 participant

Read full topic

🏷️ rust_feed