Generic function on tuple elements

⚓ rust    📅 2025-07-15    👤 surdeus    👁️ 2      

surdeus

Is there a way to write a generic function that iterates over the elements of a tuple and applies the given generic function to each element individually?

The following approach does not compile:

trait TupleDo {
    fn foreach<E>(&self, handle: impl Fn(&E));
}
impl<T> TupleDo for (T,) {
    fn foreach<E>(&self, handle: impl Fn(&E)) {
        handle(&self.0);
        // calling error here
        // mismatched types
        // expected reference `&E`
        //    found reference `&T`
        // a type parameter was expected, but a different one was found; you might be missing a type parameter or trait bound
    }
}

impl<T1,T2> TupleDo for (T1,T2) {
    fn foreach<E>(&self, handle: impl Fn(&E)) {
        let e1 = &self.0;
        let e2 = &self.0;
        handle(e1); // error same as above
        handle(e2); // error same as above
    }
}

fn do_each_elment<T:Debug>(t:T) {
    println!("{t:?}");
}

fn analyze_tup<T:TupleDo>(t:T) {
    t.foreach(do_each_elment);
    // error comes here:
    // type annotations needed
    // cannot infer type of the type parameter `T` declared on the function `do_each_elment`rustcClick for full compiler diagnostic
    // lib.rs(270, 29): consider specifying the generic argument: `::<&E>`
}

fn test_tuple_do() {
    analyze_tup((3,));   
    analyze_tup((3,4));   
}

Any suggestions or insights would be greatly appreciated.

1 post - 1 participant

Read full topic

🏷️ rust_feed