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 :
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();