Is it possible to handle different numbers of elements inside a flat_map
in Rust?
I have a case where based on a condition I need to either map a single enum
element or a vector of enum
elements.
I tried to use std::iter::once
but it's not working since once
and Vec::iter
are different types the could not be returned from the same if
condition.
enum Enum {
Ident(String),
Val(i32),
}
fn main() {
let my_vec = vec![1, 2, 3];
let condition = true; // Any condition
my_vec
.iter()
.flat_map(|x| {
if condition {
std::iter::once(Enum::Ident("id".to_string())).into_iter() /* single Enum element */
} else {
vec![Enum::Val(1), Enum::Val(2)].iter() /* vector of Enum elements */
}
})
.collect::<Vec<Enum>>()
}
error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:16:17
|
13 | / if condition {
14 | | std::iter::once(Enum::Ident("id".to_string())).into_iter() /* single Enum element */
| | ---------------------------------------------------------- expected because of this
15 | | } else {
16 | | vec![Enum::Val(1), Enum::Val(2)].iter() /* vector of Enum elements */
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::iter::Once`, found struct `std::slice::Iter`
17 | | }
| |_____________- `if` and `else` have incompatible types
|
= note: expected type `std::iter::Once<Enum>`
found struct `std::slice::Iter<'_, Enum>`