rust - What is the advantage of using the same lifetime for multiple arguments? -
fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { x }
what advantage of above code on using 2 lifetimes? there situations in above code work, 2 lifetimes won't?
it depends on use case. given exact code wrote:
fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { x }
here disadvantage use 1 lifetime, because return value depends on x
argument, not on y
one. let's imagine user code:
let x_in = "paul".to_owned(); let out = { let y_in = "peter".to_owned(); xory(&x_in, &y_in) };
we expect works fine, because out
x_in
. compiler complains:
<anon>:12:22: 12:26 error: `y_in` not live long enough <anon>:12 xory(&x_in, &y_in) ^~~~ <anon>:13:7: 14:2 note: reference must valid block suffix following statement 1 @ 13:6... <anon>:13 }; <anon>:14 } <anon>:11:39: 13:6 note: ...but borrowed value valid block suffix following statement 0 @ 11:38 <anon>:11 let y_in = "peter".to_owned(); <anon>:12 xory(&x_in, &y_in) <anon>:13 };
this because compiler assumes (from xory
signature) output xory
references both arguments. it's better specify lifetimes detailed possible avoid unnecessary conditions/assumptions/relationships between parameters.
in cases need use 1 lifetime (or different solution): suppose want return either x
or y
depending on condition:
fn xory<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() == 42 { x } else { y } }
here lifetime of output can depend on both arguments' lifetimes , don't know on 1 @ compile time. therefore have prepare worst , this.
Comments
Post a Comment