Why can impl trait not be used to return multiple / conditional types?

impl Trait is not equivalent to returning an interface or base class object. It’s a way of saying “I don’t want to write the name of the specific type I’m returning”. You’re still returning a value of a single, specific type; you just aren’t saying which type.

Each of those branches is returning different types, hence the problem. Implementing the same trait is not enough.

What you likely want in this specific case is a trait object like Box<dyn RngCore>.

extern crate rand; // 0.6.5

use rand::{rngs::OsRng, thread_rng, RngCore};

fn rng() -> Box<dyn RngCore> {
    match OsRng::new() {
        Ok(rng) => Box::new(rng),
        Err(_) => Box::new(thread_rng()),
    }
}

Note: if you are using a slightly older version of Rust, you may need to remove the dyn keyword. It’s optional in the previous (2015) edition of Rust.

Leave a Comment