Workaround recursion limit while instantiating with generics

Hello,

I have a recursive generic function which raises the error recursion limit while instantiating. I made a code snippet below, also available in the playground.

What would your recommend as a rewrite workaround for the recurse function, please ?

use std::io::{self, Cursor, Read, Take};

fn recurse<T: Read>(f: Foo<T>, i: u32) {
    println!("i = {}", i);
    if i < 2 {
        let f = f.child();
        recurse(f, i + 1);
    }
}

struct Foo<T> {
    t: T,
}

impl<T: Read> Read for Foo<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.t.read(buf)
    }
}

impl<T: Read> Foo<T> {
    fn child(self) -> Foo<Take<T>> {
        Foo { t: self.t.take(10) }
    }
}

fn main() {
    let c = Cursor::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
    let f = Foo { t: c };
    recurse(f, 0);
}
use std::io::{self, Cursor, Read, Take};

fn recurse<T: Read>(f: Foo<T>, i: u32) {
    println!("i = {}", i);
    if i < 2 {
        let mut f = f.child();
        recurse(f.as_mut_read(), i + 1);
    }
}

..

impl<T: Read> Foo<T> {
    fn as_mut_read(&mut self) -> Foo<&mut Read> {
        Foo { t: &mut self.t }
    }

    ..
}
1 Like

Excellent thank you very much !