Search code examples
rusttraitsassociated-types

How do I define trait bounds on an associated type?


I want to write a function that accepts Iterator of type that has ToString trait.

What I have in mind:

fn parse<T: Iterator /* ?T::Item : ToString? */>(mut args: T) -> Result<String, String> {
    match args.next() {
        Some(x) => x.to_string(),
        None => String::from("Missing parameter"),
    }
}

Solution

  • Yes, you can do that with a where clause:

    fn parse<T: Iterator>(mut args: T) -> Result<String, String>
    where 
        <T as Iterator>::Item: ToString,
    {
       // ....
    }
    

    Or, since it's unambiguous which Item is meant here, the bound can just be:

    where T::Item: ToString