Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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"),
    }
}
like image 553
nothrow Avatar asked Jan 18 '19 16:01

nothrow


People also ask

What are trait bounds?

Trait and lifetime bounds provide a way for generic items to restrict which types and lifetimes are used as their parameters. Bounds can be provided on any type in a where clause.

Can traits have fields rust?

Traits can't have fields. If you want to provide access to a field from a trait, you need to define a method in that trait (like, say, get_blah ).

What are associated types in Rust?

Associated Types in Rust are similar to Generic Types; however, Associated Types limit the types of things a user can do, which consequently facilitates code management. Among the Generic Types of traits, types that depend on the type of trait implementation can be expressed by using the Associated Type syntax.


2 Answers

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.

like image 119
Chronial Avatar answered Sep 21 '22 13:09

Chronial


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
like image 24
Peter Hall Avatar answered Sep 19 '22 13:09

Peter Hall