Rust IO reading numbers from stdin

Hi. What is the best way to do something like this

int a, b;
std::cin >> a >> b;

in rust?
This is my current solution

let mut s = String::new();
io::stdin()
   .read_line(&mut s)
   .unwrap();

let (a,b ): (i32, i32) = {
    let x: Vec<_> = s.trim().split(' ').collect();
    (x[0].parse().unwrap(), x[1].parse().unwrap())
};

This is for competetive programming so all the data is correct.

Is your goal to do this efficiently or to do this with minimal boilerplate you have to write? Because, for efficiency, the Vec should be eliminated, but that will require writing a bit more code.

minimal boilerplate

Well, then, here's a way to get the numbers without repeating .parse().unwrap() for each one, if they are all i32s.

let x: Vec<i32> = s.trim().split(' ').map(|s| s.parse().unwrap()).collect();
let [a, b] = *x else { panic!() };

Ordinarily I would recommend Itertools::collect_array but presumably you are not allowed to use additional libraries.

2 Likes