Reducing code repetition with Vecs and fields
⚓ Rust 📅 2026-03-28 👤 surdeus 👁️ 10I am working on some code that needs to do nearly identical things on 4 total items. I am looking for a way to simplify this logic, so I don't have 4 nearly identical match statements.
Thanks in advance!
I have a Vec of 2 items, each with 2 fields.
Currently I have 4 separate match statements that all have the exact same code in them, with one difference between the two items in the vec, which of the end1/end2 variables to assign to.
Right now, this is just copy/pasted between match statements, but the code is going to get more complex and I don't want to have to maintain 4 separate copies.
In theory, only 2 of the total 4 match statements should ever actually trigger but I have simplified the code a bit here.
let mut end1 = Pos2;
let mut end2 = Pos2;
let connections: Vec<Connection> = Vec::new();
//Populate connections vec here
// connections could have more than 2 items in it, so match on case where len() == 2
match connections.len().cmp(&2) {
Ordering::Equal => {
match &connections[0].end1 {
Type1 => {
//perform logic here matching on type of connections[0].end1
let new_position = Pos2::ZERO;
end1 = new_position;
}
_ => {
todo!()
}
}
match &connections[0].end2 {
Type1 => {
//perform logic here matching on type of connections[0].end1
let new_position = Pos2::ZERO;
end1 = new_position;
}
_ => {
todo!()
}
}
match &connections[1].end1 {
Type1 => {
//perform logic here matching on type of connections[0].end1
let new_position = Pos2::ZERO;
end2 = new_position;
}
_ => {
todo!()
}
}
match &connections[1].end2 {
Type1 => {
//perform logic here matching on type of connections[0].end1
let new_position = Pos2::ZERO;
end2 = new_position;
}
_ => {
todo!()
}
}
}
Ordering::Less | Ordering::Greater => {
todo!();
}
}
If folks are interested or need more context, the actual code is here, starting at line 123
3 posts - 3 participants
🏷️ Rust_feed