我写了以下代码:
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生存期可以修复该错误?
发布于 2018-03-27 17:52:13
任何返回引用的函数都必须包含此引用的生存期。如果函数还接受至少一个按引用参数,则lifetime elision意味着您可以省略返回生命周期,但如果没有按引用参数,则不会发生省略,就像您的示例中一样。
请注意,在您的示例中,使用显式的'static生存期比使用泛型更有意义,因为您返回的值始终为'static
fn to_spelling_1(d: u8) -> &'static str {
DIGIT_SPELLING[d as usize]
}https://stackoverflow.com/questions/49509358
复制相似问题