[英]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.我想编写一个接受具有ToString
特性的Iterator
类型的函数。
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"),
}
}
Yes, you can do that with a where
clause:是的,您可以使用where
子句做到这一点:
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:或者,由于Item
在这里的含义是明确的,因此界限可以是:
where T::Item: ToString
You can use the Item =
syntax :您可以使用Item =
语法:
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:这允许您使用impl
语法进一步简化:
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.我认为这是一个更具可读性的替代方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.