gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:34:52 25 4
gpt4 key购买 nike

我写了下面的代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com