为什么我需要为返回引用的函数添加生命周期? [英] Why do I need to add a lifetime to a function that returns a reference?
问题描述
我编写了以下代码:
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);
}
此代码编译并运行没有错误.为什么我需要增加'a
寿命?为什么添加'a
有效期可以解决该错误?
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?
推荐答案
任何返回引用的函数都必须包含此引用的生存期.如果该函数还使用至少一个by-reference参数,则终身淘汰表示您可以省略返回寿命,但是如果没有by-reference参数,就不会出现省略,就像您的示例一样.
Any function that returns a reference must include a lifetime for this reference. If the function also takes at least one by-reference parameter then lifetime elision means that you can omit the return lifetime, but elision does not occur if there is no by-reference parameter, like in your example.
请注意,在您的情况下,使用显式的'static
生命周期而不是泛型会更有意义,因为您返回的值始终为'static
:
Note that in your case, it would make more sense to use an explicit 'static
lifetime rather than a generic since the value you return is always 'static
:
fn to_spelling_1(d: u8) -> &'static str {
DIGIT_SPELLING[d as usize]
}
这篇关于为什么我需要为返回引用的函数添加生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!