Closed
Description
In the code below Rust fails to infer an appropriate lifetime, even though y
and w
clearly both live long enough to compare them.
Note that the suggested fix of giving the &str
contained in y
the lifetime 'a
is undesirable in case y
lives shorter than x
and the returned value.
fn test<'a>(x: &'a Option<String>, y: Option<&str>) -> Option<&'a Option<String>> {
let w = x.as_ref().map(|z| z.as_slice());
if y == w {
return Some(x);
}
None
}
fn main() {
let x = Some("asdf".to_string());
println!("{}", test(&x, Some("foo")));
}
<anon>:1:1: 7:2 note: consider using an explicit lifetime parameter as shown: fn test<'a>(x: &'a Option<String>, y: Option<&'a str>) ->
Option<&'a Option<String>>
<anon>:1 fn test<'a>(x: &'a Option<String>, y: Option<&str>) -> Option<&'a Option<String>> {
<anon>:2 let w = x.as_ref().map(|z| z.as_slice());
<anon>:3 if y == w {
<anon>:4 return Some(x);
<anon>:5 }
<anon>:6 None
...
<anon>:2:13: 2:23 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
<anon>:2 let w = x.as_ref().map(|z| z.as_slice());
^~~~~~~~~~
error: aborting due to previous error
playpen: application terminated with error code 101