2
votes

Is it possible to pass traits as parameters to generic functions like this?

trait Fnord {
    fn do_it(&self) -> i32 { 42 }
}

impl Fnord for i32 {}

fn iter_as<'a, T>(objs: &'a [i32]) -> impl Iterator<Item = & 'a dyn T>
{
    objs.iter().map(|o| o as &dyn T)
}

fn main() {
    let objs: Vec<i32> = vec![1, 2, 3];

    // Calls would look like this
    for s in iter_as::<Fnord>(&objs) {
        println!("{}", s.do_it());
    }
}

This produce me these errors:

error[E0404]: expected trait, found type parameter `T`
 --> src/lib.rs:7:69
  |
7 | fn iter_as<'a, T>(objs: &'a [i32]) -> impl Iterator<Item = & 'a dyn T>
  |                                                                     ^ not a trait

error[E0404]: expected trait, found type parameter `T`
 --> src/lib.rs:9:35
  |
9 |     objs.iter().map(|o| o as &dyn T)
  |                                   ^ not a trait

warning: trait objects without an explicit `dyn` are deprecated
  --> src/lib.rs:16:24
   |
16 |     for s in iter_as::<Fnord>(&objs) {
   |                        ^^^^^ help: use `dyn`: `dyn Fnord`
   |
   = note: `#[warn(bare_trait_objects)]` on by default

That is, can iter_as accept a trait as a generic parameter so that it can return an iterable of that trait? I've searched quite a bit for an answer, but at this point I feel like I may be asking the wrong question.

The background is like this. I've got a struct with several vectors of different concrete types, all of which implement the same traits. I'd like the struct's impl to have a function that can return an iterable over all of the stored objects as any of their common traits. The iter_as above is a simplified version of that (notional) function. Perhaps I'm simply approaching this in an awkward way for rust (i.e. maybe I'm thinking too much like a C++ programmer), so an alternative, idiomatic approach would be great, too.

1
I think that you want HRTB. That does not exist in Rust.Boiethios
It looks like some form of HRTB exists in rust (doc.rust-lang.org/nomicon/hrtb.html), but it seems to be focused on applying unspecifieable lifetimes to traits. Maybe I'm missing the point, though. How would this let me pass traits as a generic parameter?abingham
I was talking about rank-N types, but maybe I'm wrong hereBoiethios
Your MCVE is bad, you could expose your real problem "The background is like this. I've got a struct with several vectors of different concrete types, all of which implement the same traits. I'd like the struct's impl to have a function that can return an iterable over all of the stored objects as any of their common traits.", if you want a idiomatic solution you will have to produce a MCVE that show your requirement. Because for people like me that are bad in english is not really clear. specially the end is unclear.Stargateur

1 Answers

3
votes

T must be a concrete type and not a trait. The closer to what you're looking for that I can think to is the following:

trait Fnord {
    fn do_it(&self) -> i32;
}

impl Fnord for i32 {
    fn do_it(&self) -> i32 {
        *self
    }
}

impl<'a> From<&'a i32> for &'a dyn Fnord {
    fn from(i: &'a i32) -> Self {
        i as _
    }
}

fn iter_as<'a, T, TObj>(objs: &'a [T]) -> impl Iterator<Item = TObj> + 'a
where
    TObj: 'a,
    TObj: From<&'a T>,
{
    objs.iter().map(|o| o.into())
}

fn main() {
    let objs: Vec<i32> = vec![1, 2, 3];

    for s in iter_as::<i32, &dyn Fnord>(&objs) {
        println!("{}", s.do_it()); // 1 2 3
    }
}

I'm not sure that you've chosen the idiomatic Rust way to do that: since you know the concrete types that are in your object, you can write it as follow:

trait Fnord {
    fn do_it(&self) -> i32;
}

impl Fnord for i32 {
    fn do_it(&self) -> i32 {
        *self
    }
}

impl<'a> From<&'a i32> for &'a dyn Fnord {
    fn from(i: &'a i32) -> Self {
        i as _
    }
}

struct YourObject {
    v1: Vec<i32>,
    v2: Vec<i32>,
}

impl YourObject {
    fn iter_as<'a, T>(&'a self) -> impl Iterator<Item = T> + 'a
    where
        T: From<&'a i32>, // Add the other bounds you need
    {
        self.v1
            .iter()
            .map(|o| o.into())
            .chain(self.v2.iter().map(|o| o.into()))
    }
}

fn main() {
    let obj = YourObject {
        v1: vec![1, 2],
        v2: vec![3],
    };

    for s in obj.iter_as::<&dyn Fnord>() {
        println!("{}", s.do_it()); // 1 2 3
    }
}

The From implementation boilerplate can be reduced thanks to a macro:

macro_rules! impl_from_for_dyn_trait {
    ( $concrete:ty, $trait:path ) => {
        impl<'a> From<&'a $concrete> for &'a dyn $trait {
            fn from(c: &'a $concrete) -> Self {
                c as _
            }
        }
    }
}

impl_from_for_dyn_trait!(i32, Fnord);