Lifetime conversion explanation Why is allowed?

โš“ Rust    ๐Ÿ“… 2025-11-22    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 10      

surdeus

I got a question how does this compile.

fn this_function<'a, 'b>(arg: &'a mut &'b u8) -> 
&'b mut &'a u8
{
    let a: &'a mut &'a u8 = arg;
    a
}

Is there some implicit lifetime bound, why able to โ€œswapโ€ 2 lifetimes
Also if we introduce 2 new lifetimes

fn functionthing<'a, 'b, 'c, 'd>(arg: &'a mut &'b u8) -> 
&'b mut &'a u8
where
'b: 'c, 'c: 'b,
'b: 'd, 'd: 'b,
{
    let a: &'d mut &'c u8 = arg;
    a
}

but at the bounds you can replace the bounds to

โ€˜b: โ€˜c, โ€˜c: โ€˜a,
โ€˜b: โ€˜c, โ€˜c: โ€˜b

No compile error so extrapolating to (and changing &โ€™c โ€ฆ to &โ€™d โ€ฆ)

fn functionthing<'a, 'b, 'c, 'd>(arg: &'a mut &'b u8) -> 
&'b mut &'a u8
where
/*โ€™b or โ€˜a*/: 'c, 'c: /*โ€™b or โ€˜a*/,
/*โ€™b or โ€˜a*/: 'd, 'd: /*โ€™b or โ€˜a*/,
{
    let a: &/*โ€™c or โ€˜d*/ mut &/*โ€™c orโ€™d*/u8 = arg;
    a
}

I tested some combination in rust playground but why does this work when compiling,
and does changing bounds, change the usability of this function

3 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed