我无法编译此函数:
当前存在的错误是:
/// Return a String with all characters masked as '#' except the last 4.
fn maskify(cc: &str) -> String {
let chars = cc.to_string().chars();
chars
.enumerate()
.map(|(i, c)| {
if i > chars.count() - 4 { '#' } else { c }
})
.collect()
}
当前存在的错误是:
error[E0507]: cannot move out of `chars`, a captured variable in an `FnMut` closure
--> src/lib.rs:7:21
|
3 | let chars = cc.to_string().chars();
| ----- captured outer variable
...
7 | if i > &chars.count() - 4 { '#' } else { c }
| ^^^^^ move occurs because `chars` has type `std::str::Chars<'_>`, which does not implement the `Copy` trait
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:3:17
|
3 | let chars = cc.to_string().chars();
| ^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
4 | chars
| ----- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
error[E0382]: use of moved value: `chars`
--> src/lib.rs:6:14
|
3 | let chars = cc.to_string().chars();
| ----- move occurs because `chars` has type `std::str::Chars<'_>`, which does not implement the `Copy` trait
4 | chars
| ----- value moved here
5 | .enumerate()
6 | .map(|(i, c)| {
| ^^^^^^^^ value used here after move
7 | if i > &chars.count() - 4 { '#' } else { c }
| ----- use occurs due to use in closure
我认为错误的源头在于 chars
是一个迭代器,因此它会发生变化,这使得在闭包中无法进行借用,但是即使我尝试声明一个本地变量(例如 let count = chars.count()
),我仍然会遇到借用错误。
我已经尝试使用 &
进行解引用,但也没有起作用。
cc.chars().count()
而不是cc.len()
,以更好地支持 Unicode。(虽然这仍然无法处理所有情况,但更接近了。) - Lambda Fairylen
不正确,但是添加另一个count()
就可以解决这个问题。 - mzedeler#
上的组合代码点)。 - Masklinnstr.len()
只处理 ASCII 字符,否则它完全失效(并且可以说在尝试操作字符时它根本就是有问题的)。如果使用str::len
,该函数可能会在获取非 ASCII 码点时失败,无论是完全崩溃还是只导致一个Err
。 - Masklinn