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

Getting the index length of a particular struct type

I have a custom Struct that consists of two i32 types that make out a 2D vector. I have been accessing certain indices using for loops, but I have yet to figure out how to get the length of either ‘col or ‘row’. Here’s my code:

#[derive(Debug)]
pub struct Vec2d {
    col: i32,
    row: i32,
}


fn main() {
    let mut vec_struct = Vec::new();

    for i in 0..5 {
        for j in 0..7 {  
            let index = [
                Vec2d {
                    col: j * 3,
                    row: i * 5,
                },
            ];
            vec_struct.push(index);
        }
    }

    // I want to get 5 or 7 somehow, but none of these two work
    println!("{}", vec_struct[0][0].len());
    println!("{}", vec_struct[0].len());
    
    // This works, but prints both dimensions (output: 35)
    println!("{}", vec_struct.len());
}

>Solution :

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

Since you’re storing your elements in a flat Vec, you’ve lost the information of where each column/row starts and ends.

You can either store them in a nested Vec<Vec<Vec2d>>, or try to restore this information armed with the knowledge that a new column starts when the column number is zero:

let columns = vec_struct
    .iter()
    .enumerate()
    .skip(1) // The first column is always zero, skip it
    .find_map(|(i, Vec2d { col, .. })| if *col == 0 { Some(i) } else { None })
    .unwrap();
let rows = vec_struct.len() / columns;

You stored the elements in one-element array ([Vec2d { ... }]). I guess you tried to do the first solution, but this array will always stay one-element-sized. You need to use a vector like that:

for i in 0..5 {
    let mut row = Vec::new();
    for j in 0..7 {
        let index = Vec2d {
            col: j * 3,
            row: i * 5,
        };
        row.push(index);
    }
    vec_struct.push(row);
}
let rows = vec_struct.len();
let columns = vec_struct[0].len();
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