Skip to content

Instantly share code, notes, and snippets.

@giuseppe998e
Last active April 11, 2024 07:35
Show Gist options
  • Save giuseppe998e/61d4c6782403f00721867d3a35d190d4 to your computer and use it in GitHub Desktop.
Save giuseppe998e/61d4c6782403f00721867d3a35d190d4 to your computer and use it in GitHub Desktop.
Rust lang example on how to remove a struct from a vector using the item reference
#[derive(Debug)]
struct Structure {
name: String,
}
#[derive(Debug)]
struct StructVector(Vec<Structure>);
impl StructVector {
fn by_name(&self, name: &str) -> Option<&Structure> {
self.0.iter().find(|t| t.name == name)
}
fn remove(&mut self, structure_ptr: *const Structure) {
self.0.retain(|s| !std::ptr::addr_eq(s, structure_ptr));
}
}
fn main() {
let mut structs = StructVector(vec![
Structure { name: "one".to_string() },
Structure { name: "two".to_string() },
Structure { name: "three".to_string() },
]);
println!("Before: {structs:?}");
let structure_ref = structs.by_name("one").unwrap();
structs.remove(structure_ref);
println!("After: {structs:?}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment