简体   繁体   中英

How do I call a trait method on a reference and not the referenced value?

I have a reference ( foo ) that implements the trait IntoIterator<Item = &T> . I want to call the trait method into_iter directly on foo (ie the reference itself) and not *foo (the referenced value), as seems to be happening, since the type of *foo also implements IntoIterator (albeit with Item = T ). I've tried UFCS, but even that doesn't seem to do the trick.

Here's my actual code:

fn csl_join<'a, V, T>(value: &V) -> String 
    where V: IntoIterator<Item = &'a T>, 
          T: 'a + ToString 
{
    itertools::join(value.into_iter().map(|v: &T| v.to_string()), ",")
}

I ended up solving this issue just after posting it, thanks to @LukasKalbertodt's helpful comments. It turns out I simply wanted the type bound to be &V: IntoIterator<Item = &T> , to match the intended usage in the function body (duh!).

So the code becomes:

fn csl_join<'a, 'b, V, T>(value: &'a V) -> String
    where V: 'a,
          &'a V: IntoIterator<Item = &'b T>,
          T: ToString + 'b
{
    itertools::join(value.into_iter().map(|v: &T| v.to_string()), ",")
}

I'll leave this here in case it assists someone else, by chance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM