简体   繁体   English

如何在关联类型上定义特征边界?

[英]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.

相关问题 将特征边界应用于关联类型 - Apply trait bounds to associated type 特征范围中的引用关联类型 - Reference associated type in trait bounds 如何从排名较高的特征绑定特征返回关联类型? - How do I return an associated type from a higher-ranked trait bound trait? 如何从具有关联类型的包装特征 object 获取特征 object? - How do I obtain a trait object from a wrapper trait object with an associated type? 如何将特征与使用特征的关联类型作为参数的超特征绑定? - How do I bound a trait with a supertrait that uses the trait's associated type as a parameter? 如何消除特征对象边界中关联类型的歧义? - How to disambiguate associated types in trait object bounds? 为什么需要定义特征来定义外部类型的实现? - Why do I need to define a trait to define an implementation on an external type? rust:定义一个返回非消耗迭代器的特征。 (T impls IntoIterator 和 &amp;T impls IntoIterator 的关联类型界限) - rust: Define a trait that returns a non consuming iterator. (associated type bounds for both T impls IntoIterator and &T impls IntoIterator) 如何将迭代器适配器与返回 impl Trait 作为 IntoIter 关联类型的 IntoIterator 的函数一起使用? - How do I use a iterator adapter with a function returning impl Trait as the IntoIter associated type of IntoIterator? 为什么在将高级特征边界与关联类型结合时会出现 Rust 编译错误? - Why do I get a Rust compilation error when combining higher-rank trait bounds with associated types?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM