How to loop through <T ?sized>

Hello,

I would like to enable multiple types being passed into a function.

pub fn register<T:Component+?Sized>(&mut self, id:usize, t:&T ) {
.... how do i loop through the Types in t, how to implement iterator for this?
}

You have to impl IntoIterator for T or Component (for example, with extra trait):

// suppose you are dealing with `?Sized` type [i32]:
pub trait Component {}
impl Component for [i32] {}

pub trait MyIntoIterator {
    type Item;
    fn into_my_iter(&self) -> impl Iterator<Item = Self::Item>;
}
impl MyIntoIterator for [i32] {
    type Item = i32;
    fn into_my_iter(&self) -> impl Iterator<Item = Self::Item> {
        self.iter().copied()
    }
}
pub fn register<T: Component + ?Sized + MyIntoIterator>(t: &T)
where
    <T as MyIntoIterator>::Item: std::fmt::Display,
{
    for i in t.into_my_iter() {
        println!("{i}")
    }
}
fn main() {
    register([1, 2, 3, 5, 8].as_slice())
}
2 Likes

What do you mean “the types in T”?

If T is meant to contain some sort of Vec<SomeType>, add a function on the trait Component.

trait Component {
    fn data(&self) -> &[SomeType];
}

pub fn register<T: Component + ?Sized>(t: &T) {
    for thing in t.data() {
        // do something with SomeType
    }
}

If you want to loop over all types that implement Component, that isn’t possible. Rust doesn’t have that level of reflection. Downstream crates could always add an implementation of Component, without even rebuilding fn register().

Yes, that’s what you have done. register can take any &T where T: Component + ?Sized[1].


  1. technically the ?Sized part is actually making a looser bound. Type parameters have an implicit T: Sized bound (at least in function definitions), which can be removed with the T: ?Sized syntax. ↩︎

2 Likes

Do you want to store different types implementing Component in one datastructure and iterate over this collection of heterogenous types? If so, you are looking for trait objects, which enable type erasure. So you can store Vec<Box<dyn Component>> and iterate over different components.

1 Like

thats exactly what i was looking for, thx a lot for the reply