首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我需要向返回引用的函数添加生存期?

为什么我需要向返回引用的函数添加生存期?
EN

Stack Overflow用户
提问于 2018-03-27 17:37:21
回答 1查看 2.1K关注 0票数 0

我写了以下代码:

代码语言:javascript
复制
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);
}

这将产生以下编译器错误:

代码语言:javascript
复制
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

为了解决这个问题,我将我的代码更改为:

代码语言:javascript
复制
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生存期可以修复该错误?

EN

回答 1

Stack Overflow用户

发布于 2018-03-27 17:52:13

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

请注意,在您的示例中,使用显式的'static生存期比使用泛型更有意义,因为您返回的值始终为'static

代码语言:javascript
复制
fn to_spelling_1(d: u8) -> &'static str {
    DIGIT_SPELLING[d as usize]
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49509358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档