如何在关联类型上定义特征范围? [英] How do I define trait bounds on an associated type?
本文介绍了如何在关联类型上定义特征范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个接受具有ToString
特征类型的Iterator
的函数.
I want to write a function that accepts Iterator
of type that has ToString
trait.
我的想法:
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"),
}
}
推荐答案
是的,您可以使用where
子句来做到这一点:
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,
{
// ....
}
或者,由于在这里确切地表示了Item
的含义,因此界限可以是:
Or, since it's unambiguous which Item
is meant here, the bound can just be:
where T::Item: ToString
这篇关于如何在关联类型上定义特征范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文