How do I define trait bounds on an associated type?

前端 未结 2 524
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 18:25

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

What I have in mind:

fn parse

        
相关标签:
2条回答
  • 2020-12-06 19:09

    You can use the Item = syntax:

    fn parse<I: ToString, T: Iterator<Item = I>>(mut args: T) -> Result<String, String>
    

    That allows you to simplify this further with the impl syntax:

    fn parse<T: Iterator<Item = impl ToString>>(mut args: T) -> Result<String, String>
    

    and finally:

    fn parse(mut args: impl Iterator<Item = impl ToString>) -> Result<String, String>
    

    I would consider this a more readable alternative.

    0 讨论(0)
  • 2020-12-06 19:16

    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
    
    0 讨论(0)
提交回复
热议问题