I wrote the following code:
const DIGIT_SPELLING: [&str; 10] = [
"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
];
fn to_spelling_1(d: u8) -> &str {
DIGIT_SPELLING[d as usize]
}
fn main() {
let d = 1;
let s = to_spelling_1(d);
println!("{}", s);
}
This gives the following compiler error:
error[E0106]: missing lifetime specifier
--> src/main.rs:5:28
|
5 | fn to_spelling_1(d: u8) -> &str {
| ^ expected lifetime parameter
|
= help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
= help: consider giving it an explicit bounded or 'static lifetime
To fix the problem, I changed my code to this:
const DIGIT_SPELLING: [&str; 10] = [
"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"
];
fn to_spelling_1<'a>(d: u8) -> &'a str { // !!!!! Added the lifetime. !!!!!
DIGIT_SPELLING[d as usize]
}
fn main() {
let d = 1;
let s = to_spelling_1(d);
println!("{}", s);
}
This code compiles and runs without error. Why did I need to add the 'a
lifetime? Why does adding the 'a
lifetime fix the error?