according to a tutorial this has a problem validating which reference to use:
fn main() {
let magic1 = String::from("abracadabra!");
let magic2 = String::from("shazam!");
let result = longest_word(&magic1, &magic2);
println!("The longest magic word is {}", result);
}
fn longest_word(x: &String, y: &String) -> &String {
if x.len() > y.len() {
x
} else {
y
}
}
the error will be:
error[E0106]: missing lifetime specifier
--> src/main.rs:9:38
|
9 | fn longest_word(x: &String, y: &String) -> &String {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
|
9 | fn longest_word<'a>(x: &'a String, y: &'a String) -> &'a String {
| ^^^^ ^^^^^^^ ^^^^^^^ ^^^
the solution is to use named lifetime parameters:
fn longest_word<'a>(x: &'a String, y: &'a String) -> &'a String {
if x.len() > y.len() {
x
} else {
y
}
}
my question is, even the solution is confusing. it only prefixed the parameters with the same name 'a so how could the borrow checker know which one, x or y, it should refer to?
also, why would a return type bother which parameter returns as long as the type is the same as declared?