Rust: how to combine iter(), iter::once(), and iter::empty()?

  Kiến thức lập trình

The following code works:

let a = [1, 2, 3].iter();
let b = iter::once(&456);

for i in a.chain(b) {
    println!("{}", i);
}

Output:

1
2
3
456

But now, I need to change b (depending on some condition) to be either iter() or iter::once , e.g.

let a = [1, 2, 3].iter();
let b = if some_condition {
    [4, 5, 6].iter()
} else {
    iter::once(&456)
};

for i in a.chain(b) {
    println!("{}", i);
}

But I got:

error[E0308]: `if` and `else` have incompatible types
   |
   |       let b = if some_condition {
   |  _____________-
   | |         [4, 5, 6].iter()
   | |         ---------------- expected because of this
   | |     } else {
   | |         iter::once(&456)
   | |         ^^^^^^^^^^^^^^^^ expected `Iter<'_, {integer}>`, found `Once<&{integer}>`
   | |     };
   | |_____- `if` and `else` have incompatible types
   |
   = note: expected struct `std::slice::Iter<'_, {integer}>`
              found struct `std::iter::Once<&{integer}>`

What should I do?

LEAVE A COMMENT