How to convert a number to numeric vec?


#1

How to convert this number to a numeric vec?

number = 1234
Expect:
array: Vec<i32> = [1, 2, 3, 4]


#2

I don’t think there is a Rust-specific shortcut for this. Instead you’ll have to implement it using your favorite algorithm. One example could be something like this (https://is.gd/dY4p8E):

fn number_to_vec(n: i32) -> Vec<i32> {
    let mut digits = Vec::new();
    let mut n = n;
    while n > 9 {
        digits.push(n % 10);
        n = n / 10;
    }
    digits.push(n);
    digits.reverse();
    digits
}

A different way would be to format the number as a string and then split that string into individual digits.


#3

And that is:

fn number_to_vec(n: u32) -> Vec<u32> {
    n.to_string()
        .chars()
        .map(|c| c.to_digit(10).unwrap())
        .collect()
}

#4

It looks neaty. If performance doesn’t matter


#5

@mgeisler
@bugaevc
Thank you. your solutions work for me.