Assert_eq in a for loop

This is from the "Programming Rust: Fast, Safe Systems Development" book in the section that dragged me through the Mandelbrot Set plotting thing. Other than being shown how to write to a .png file what a useless college exercise thing THAT was. It has a test section for testing the operation of the command line parser. I saw a repeated pattern that screamed "FOR LOOP!" at me, so I gave it a try. Unfortunately the loop looked at it's items and typed the array of tuples I'd set up, forcing i32. It looks like I need to finger out how to store the numeric type in the tuple and pass that along:

Original from the book

fn test_parse_pair() {
    assert_eq!( parse_pair:: < i32 >("", ','), None);
    assert_eq!( parse_pair:: < i32 >(" 10,", ','), None);
    assert_eq!( parse_pair:: < i32 >(", 10", ','), None);
    assert_eq!( parse_pair:: < i32 >(" 10,20", ','), Some(( 10, 20)));
    assert_eq!( parse_pair:: < i32 >(" 10,20xy", ','), None);
    assert_eq!( parse_pair:: < f64 >(" 0.5x", 'x'), None);
    assert_eq!( parse_pair:: < f64 >(" 0.5x1.5", 'x'), Some(( 0.5, 1.5)));
}

My for loopy thing:

fn test_parse_pair() {
    let testlist = [
    (( "", ','),       None),
    (("10,", ','),     None),
    ((",10", ','),     None),
    (("10,20", ','),   Some((10, 20))),
    (("10,20xy", ','), None),
    (("0.5x", 'x'),    None),
    (("0.5x1.5", 'x'), Some((0.5, 1.5))),
    ]; 
    for index in 0..testlist.len()
    {
        assert_eq!(parse_pair::<i32>(testlist.0),testlist.1);
    }
}
1 Like

Please read the pinned post on syntax highlighting and edit your post.

Just split it into two lists

fn test_parse_pair() {
    let i32_list = [
        (("", ','), None),
        (("10,", ','), None),
        ((",10", ','), None),
        (("10,20", ','), Some((10, 20))),
        (("10,20xy", ','), None),
    ];
    let f64_list = [
        (("0.5x", 'x'), None),
        (("0.5x1.5", 'x'), Some((0.5, 1.5))),
    ];
    for item in i32_list.into_iter() {
        assert_eq!(parse_pair::<i32>(item.0), item.1);
    }
    for item in f64_list.into_iter() {
        assert_eq!(parse_pair::<f64>(item.0), item.1);
    }
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.