Search code examples
structrustiteratortuplescollect

How do I collect tuples to a Vec of custom 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


Solution

  • 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>>()
    }