我正在编写一个函数,需要将大整数拆分为个位数字,以便进行操作。
我尝试了以下方法:
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());
但那看起来甚至更为做作。
有没有更好、更自然的方法呢?