【发布时间】:2017-05-23 00:47:31
【问题描述】:
我正在编写一个函数,该函数需要较大整数的各个数字来执行操作。
我尝试了以下方法:
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());
但这看起来更加做作。
有没有更好的,可能更自然的方式来做到这一点?
【问题讨论】:
-
我为此写了一个板条箱:docs.rs/digits_iterator