我正在写一个函数,它需要一个更大整数的各个数字来对其执行操作.
我试过以下方法:
fn example(num: i32) {
// I can safely unwrap because I know the chars of the string are going to be valid
let digits = num.to_string().chars().map(|d| d.to_digit(10).unwrap());
for digit in digits {
println!("{}", digit)
}
}
但借书判断人员表示,这根绳子的生命周期 不够长:
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:3:18
|
3 | let digits = num.to_string().chars().map(|d| d.to_digit(10).unwrap());
| ^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
4 | for digit in digits {
| ------ borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
以下方法确实有效:
let temp = num.to_string();
let digits = temp.chars().map(|d| d.to_digit(10).unwrap());
但这看起来更加做作.
有没有更好、更自然的方法?