How do I define trait bounds on an associated type?

大兔子大兔子 提交于 2019-12-11 00:58:59

问题


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"),
    }
}

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/54258253/how-do-i-define-trait-bounds-on-an-associated-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!