reference - 为什么我需要为返回引用的函数添加生命周期?

标签 reference rust lifetime

我写了下面的代码:

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 生命周期可以修复错误?

最佳答案

任何返回引用的函数都必须包含该引用的生命周期。如果该函数还采用至少一个引用参数,则 lifetime elision意味着您可以省略返回生命周期,但如果没有引用参数,则不会发生省略,就像您的示例中那样。

请注意,在您的情况下,使用显式 'static 生命周期而不是泛型会更有意义,因为您返回的值始终是 'static:

fn to_spelling_1(d: u8) -> &'static str {
    DIGIT_SPELLING[d as usize]
}

关于reference - 为什么我需要为返回引用的函数添加生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49509358/

相关文章:

c++ - 设置引用c++

c++ - 通过C++中的引用声明传递

c++ - 双向链表添加元素

rust - 如何将 Rust 中的范围转换为切片?

python - 使用 ctypes 在 Python 中使用 Rust 返回的数组

rust - 有没有办法对结构的实例执行索引访问?

rust - 结构持有的特征对象中的显式生命周期声明

rust - 如何分配给匹配分支内的匹配表达式中使用的变量?