如何将整数拆分成单个数字?

18

我正在编写一个函数,需要将大整数拆分为个位数字,以便进行操作。

我尝试了以下方法:

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());

但那看起来甚至更为做作。

有没有更好、更自然的方法呢?


我已经为此编写了一个crate:https://docs.rs/digits_iterator/ - Boiethios
1个回答

31

但是借用检查器说这个字符串的生命周期不够长。

那是因为它确实不够长。你没有使用迭代器,所以digits的类型是

std::iter::Map<std::str::Chars<'_>, <closure>>

也就是说,这是一个尚未评估的迭代器,其中包含对已分配字符串的引用(Chars 中的未命名生命周期'_')。但是,由于该字符串没有所有者,在语句结束之前就已被删除;在迭代器被消耗之前。

因此,Rust避免了使用后释放的错误!

消耗迭代器将“解决”问题,因为对已分配字符串的引用不会试图比已分配字符串存在更长时间;它们都在语句结束时终止:

let digits: Vec<_> = num.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect();

如果您想要返回一个迭代器,那么您可以将 Vec 转换回迭代器:

fn digits(num: usize) -> impl Iterator<Item = u32> {
    num.to_string()
        .chars()
        .map(|d| d.to_digit(10).unwrap())
        .collect::<Vec<_>>()
        .into_iter()
}
关于另一种解决方案,可以从C++问题 “获取int中的每个数字” 偷来数学方法创建一个向量:


fn x(n: usize) -> Vec<usize> {
    fn x_inner(n: usize, xs: &mut Vec<usize>) {
        if n >= 10 {
            x_inner(n / 10, xs);
        }
        xs.push(n % 10);
    }
    let mut xs = Vec::new();
    x_inner(n, &mut xs);
    xs
}

fn main() {
    let num = 42;
    let digits: Vec<_> = num.to_string().chars().map(|d| d.to_digit(10).unwrap()).collect();
    println!("{:?}", digits);
    let digits = x(42);
    println!("{:?}", digits);
}

然而,您可能需要为负数添加所有特殊情况逻辑,并进行测试也不是坏主意。

您可能还想要一个花式迭代器版本:

fn digits(mut num: usize) -> impl Iterator<Item = usize> {
    let mut divisor = 1;
    while num >= divisor * 10 {
        divisor *= 10;
    }

    std::iter::from_fn(move || {
        if divisor == 0 {
            None
        } else {
            let v = num / divisor;
            num %= divisor;
            divisor /= 10;
            Some(v)
        }
    })
}

或完全自定义类型:

struct Digits {
    n: usize,
    divisor: usize,
}

impl Digits {
    fn new(n: usize) -> Self {
        let mut divisor = 1;
        while n >= divisor * 10 {
            divisor *= 10;
        }

        Digits {
            n: n,
            divisor: divisor,
        }
    }
}

impl Iterator for Digits {
    type Item = usize;

    fn next(&mut self) -> Option<Self::Item> {
        if self.divisor == 0 {
            None
        } else {
            let v = Some(self.n / self.divisor);
            self.n %= self.divisor;
            self.divisor /= 10;
            v
        }
    }
}

fn main() {
    let digits: Vec<_> = Digits::new(42).collect();
    println!("{:?}", digits);
}

另请参阅:


我不明白这怎么会成为一个使用后释放漏洞。它不是会立即被使用,然后才被释放吗? - Electric Coffee
关于为负数添加特殊情况测试:使用u32的函数永远不会出现负数。 - Electric Coffee
3
使用to_string会创建一个临时变量,其寿命仅限于创建它的语句。然而,您的digits迭代器引用该临时变量,但其生命周期要长得多,这是不正确的。如果您在同一语句中立即调用collect,则就不存在问题了。 - Matthieu M.
你比我先做到了,@MatthieuM.! - Shepmaster
1
如果性能是一个问题,可以进一步优化,使用/100而不是/10,并使用查找表来处理100个可能性,每次产生2个数字。我假设编译器可以将%和/融合成单个指令。 - the8472
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接