简体   繁体   中英

How do I implement a FromIterator trait for my struct?

use itertools::Itertools;

struct Runner {
    h: u8,
    m: u8,
    s: u8,
}

impl Runner {
    fn from(v: (u8,u8,u8)) -> Runner {
        Runner {
            h: v.0,
            m: v.1,
            s: v.2,
        }
    }
}

fn string_to_vec(strg: &str) -> Vec<Runner> {
    strg.split(", ")
        .map(|personal_result| personal_result.split('|'))
        .flatten()
        .map(|x| x.parse::<u8>().unwrap())
        .tuples::<(_, _, _)>()
        .collect::<Vec<Runner>>()
} 
    
fn stati(strg: &str) -> String {
    let run_vec = string_to_vec(strg);
}

So I'm trying to collect tuples to a Vec of my struct. Can't figure out how to do so https://www.codewars.com/kata/55b3425df71c1201a800009c/train/rust

Your from() function will not be call magically, even if you implement the trait From , you need to explicitly call it:

use itertools::Itertools;

struct Runner {
    h: u8,
    m: u8,
    s: u8,
}

impl From<(u8, u8, u8)> for Runner {
    fn from(v: (u8, u8, u8)) -> Runner {
        Runner {
            h: v.0,
            m: v.1,
            s: v.2,
        }
    }
}

fn parse_runner(strg: &str) -> Vec<Runner> {
    strg.split(", ")
        .flat_map(|personal_result| personal_result.split('|'))
        .map(|x| x.parse::<u8>().unwrap())
        .tuples::<(_, _, _)>()
        .map(From::from)
        .collect::<Vec<Runner>>()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM