Dan Cojocaru
Dan Cojocaru

Reputation: 167

Return different kinds of iterators in flat_map

In the following snippet of code, Rust complains that the return types do not match.

let line = String::new();    // assume string has content
let line: String = line.bytes()
    .flat_map(|b| {
        if b > 0x7F {
            format!("M-{}", char::from(b - 0x7F)).bytes()
        }
        else {
            [b].into_iter()    // error happens here
        }
    })
    .map(|b| { char::from(b) })
    .collect();

The error is the following:

if and else have incompatible types
expected type std::str::Bytes<'_>
found struct std::slice::Iter<'_, u8>

How can I avoid this?

Upvotes: 1

Views: 550

Answers (1)

Dan Cojocaru
Dan Cojocaru

Reputation: 167

I got the answer here.

The easiest solution is to use the either crate.

Upvotes: 0

Related Questions