我写了以下代码:
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);
}
这会产生以下编译器错误:
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
要解决此问题,我将代码更改为:
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);
}
此代码编译并运行且没有错误。为什么我需要添加'a
生命周期?为什么添加'a
生命周期会修复错误?
答案 0 :(得分:1)
任何返回引用的函数都必须包含此引用的生命周期。如果该函数也至少采用一个by-reference参数,则lifetime elision表示您可以省略返回生命周期,但如果没有by-reference参数,则不会出现省略,如示例所示。
请注意,在您的情况下,使用明确的'static
生命周期而不是通用更有意义,因为您返回的值始终为'static
:
fn to_spelling_1(d: u8) -> &'static str {
DIGIT_SPELLING[d as usize]
}