Last active
April 11, 2024 07:35
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[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