Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rewrite this generic arg?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading