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"),
}
}
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.
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 ).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With