Home > other >  How to rewrite this generic arg?
How to rewrite this generic arg?

Time:12-13

In a function one should be able to send a String and receive Vec<usize> or HashSet<i32>. It is already working (see below):

fn line<T: FromIterator<A>, A: FromStr>(str: String) -> Result<T, &'static str> {

but, since it takes 2 generic args, you have to write something like the following:

line<Vec<usize>, _>()?;

Is there a way to write it with only one generic argument? Perhaps similar to:

// This doesn't work!
fn line<T: FromIterator<A: FromStr>>(str: String) -> Result<T, &'static str> {

The goal is to be able to write calls this way (only one generic):

line<Vec<usize>>()?;

Docs: std::iter::FromIterator, Generic Types, Traits, and Lifetimes, Generic parameters, Trait and lifetime bounds.

CodePudding user response:

You use an opaque impl Trait. playground

use std::str::FromStr;

fn line<T: FromIterator<impl FromStr>>(str: String) -> Result<T, &'static str> {
    todo!()
}

fn main() {
    line::<Vec<String>>("".into());
}

See rust book.

  • Related