【发布时间】:2021-02-02 22:03:58
【问题描述】:
我正在通过一些 LeetCode 挑战来加深对 Rust 的理解。我正在尝试编写以下程序,该程序接受i32 输入,将其转换为String,反转数字并返回i32 数字。
在负数的情况下,例如-132,当数字反转时,连字符必须从堆栈中弹出:-132 -> 231- -> 231。
我已经编写了以下代码,但遇到了借用检查器,有人可以帮忙吗?
impl Solution {
pub fn reverse(x: i32) -> i32 {
if(x == 0){
return x;
}
let reversed : std::iter::Rev<std::str::Chars> = x.to_string().chars().rev();
if reversed.last().unwrap() == '-' { //error occurs here
return reversed.collect::<String>()[0..reversed.count()].parse::<i32>().unwrap();
} else {
return reversed.collect::<String>().parse::<i32>().unwrap();
}
}
}
Line 6, Char 61: temporary value dropped while borrowed (solution.rs)
|
6 | let reversed : &std::iter::Rev<std::str::Chars> = &x.to_string().chars().rev();
| ^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
7 | if reversed.last().unwrap() == '-' {
| -------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
Line 7, Char 12: cannot move out of `*reversed` which is behind a shared reference (solution.rs)
|
7 | if reversed.last().unwrap() == '-' {
| ^^^^^^^^ move occurs because `*reversed` has type `std::iter::Rev<std::str::Chars<'_>>`, which does not implement the `Copy` trait
Line 8, Char 20: cannot move out of `*reversed` which is behind a shared reference (solution.rs)
|
8 | return reversed.collect::<String>()[0..reversed.count()].parse::<i32>().unwrap();
| ^^^^^^^^ move occurs because `*reversed` has type `std::iter::Rev<std::str::Chars<'_>>`, which does not implement the `Copy` trait
Line 8, Char 52: cannot move out of `*reversed` which is behind a shared reference (solution.rs)
|
8 | return reversed.collect::<String>()[0..reversed.count()].parse::<i32>().unwrap();
| ^^^^^^^^ move occurs because `*reversed` has type `std::iter::Rev<std::str::Chars<'_>>`, which does not implement the `Copy` trait
Line 10, Char 20: cannot move out of `*reversed` which is behind a shared reference (solution.rs)
|
10 | return reversed.collect::<String>().parse::<i32>().unwrap();
| ^^^^^^^^ move occurs because `*reversed` has type `std::iter::Rev<std::str::Chars<'_>>`, which does not implement the `Copy` trait
这是playground中重现的错误
【问题讨论】:
-
请在问题中包含错误信息。另外,请说明您是否阅读了整个错误(不仅仅是标记线上的部分)。如果是这样,您是否尝试理解并实施编译器的建议?
-
@user4815162342 是的,肯定地阅读了整个错误几次,我来回尝试使
reversed成为对x的引用而不是直接引用该值,但会不断遇到各种各样的问题的错误。我已经用错误更新了问题。 -
好的,所以编译器告诉您“值的寿命不够长”,并提示“考虑使用
let绑定来创建寿命更长的值”。它表明x.to_string()创建的临时值不够长。您可以从let s = x.to_string()(编译器引用的let绑定)开始,然后改用s。这允许reversed迭代器引用实际存在的值所拥有的字符(因为它在let绑定中,保证在绑定超出范围之前一直存在)。
标签: rust reference lifetime borrow-checker borrowing