Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create vector with 0 or 1 elements from an Option

Tags:

rust

Is there a shorter and simpler way to achieve this:

let o: Option<i32> = ...;
let ve: Vec<i32> = match o {
    None => vec![],
    Some(n) => vec![n],
};
like image 552
at54321 Avatar asked Jan 20 '26 22:01

at54321


2 Answers

Option implements IntoIterator, so you can make an iterator and collect it:

let ve: Vec<i32> = o.into_iter().collect();
like image 128
Peter Hall Avatar answered Jan 23 '26 12:01

Peter Hall


let o: Option<i32> = Some(2);
let ve: Vec<i32> = o.into_iter().collect();

Playground Link

like image 35
Mihir Luthra Avatar answered Jan 23 '26 10:01

Mihir Luthra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!