kuity
1
If I am reading in some input which is following a known format, in Python can write like:
[n, q] = [int(x) for x in next(some_input).strip().split(' ')]
In rust, so far I have:
let v: Vec<i32> = some_input.next().unwrap().split(' ').map(|s| s.parse().unwrap()).collect();
let n = v[0];
let q = v[1];
Is there a way to concisely assign v[0] and v[1] to variables n and q?
L.F
2
You can use a pattern:
let (n, q) = match v.as_slice() {
&[n, q] => (n, q),
_ => return Err(...), // len() != 2
}
1 Like
kuity
3
I see, thanks for your reply.
That's a useful pattern, but for my case I wanted to know if there's something less verbose, like a one-liner.
ZiCog
4
I think you might want ".take(2)".
For example:
let s:String = "1 2 3".to_string();
let input: Vec<i32> = s.split(" ").take(2).map(|s| s.parse().unwrap() ).collect();
println!("{:?}", input);
Produces "[1, 2]"
1 Like
system
Closed
5
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.