0

I'm learning Rust and am messing around with conversions of types because I need it for my first program.

Basically I'm trying to convert a singular string of numbers into an array of numbers.

eg. "609" -> [6,0,9]

const RADIX: u32 = 10;
let lines: Vec<String> = read_lines(filename);

let nums = lines[0].chars().map(|c| c.to_digit(RADIX).expect("conversion error"));

println!("Line: {:?}, Converted: {:?}", lines[0], nums);

I tried the above and the output is as follows:

Line: "603", Converted: Map { iter: Chars(['6', '0', '3']) }

Which I assume isn't correct. I'd need it to be just a pure array of integers so I can perform operations with it later.

3
  • Rust iterators are lazy. This means that iterating over your string characters and applying adapters does not do actually anything except creating a variable of type Map. Only when you call collect, this is when the iteration actually occurs. Commented Aug 2, 2022 at 20:52
  • Also note that this is not going to work as you expect if you every change the RADIX, because the string "609" is already in base 10. If you wanted to gets the digits in an other base, you'd have to convert that string to a number first, and then get the digits. Commented Aug 3, 2022 at 6:19
  • Good to know, but I don't need to do that in this context, so it's all good. Commented Aug 5, 2022 at 16:13

1 Answer 1

3

You're almost there, add the type ascription to nums:

let nums: Vec<u32> = ...

and end the method chain with .collect() to turn it into a vector of digits.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.