我想要编写一个函数,可以将一个字符串反转并返回该字符串的引用。我认为我应该能够指定返回的引用与提供的引用具有相同的生命周期。
fn reverse_string<'a>(input: &'a str) -> &'a str {
let res: &'a str = input.chars().rev().collect().as_slice();
res
}
这是我的尝试,但我收到了错误提示:
error[E0282]: type annotations needed
--> src/lib.rs:2:24
|
2 | let res: &'a str = input.chars().rev().collect().as_slice();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type for `B`
|
= note: type must be known at this point
我原本认为类型规范可以解决这个问题。生命周期对我来说有点困惑,所以我希望有人能够解释如何正确地处理这个问题,或者如果我一开始就完全错误的话。
collect
添加注释吗?如果需要,你可以使用let v: Vec<char> = ...;
或者collect::<Vec<char>>()
. - Matthieu M.e
后跟́
后跟o
,则́
将附加到e
:éo
,但在反转后,它将附加到o
:óe
。 - Matthieu M.