I wrote some sample code trying to practice certain concepts I had learnt, (lifetimes, implementing methods for structs and other concepts). Below is sample code that works:
fn main() {
let structure1 = Structure{num: 4f64, string: "Raggamuffin"};
let structure2 = Structure{num: 5f64, string: "Dutty Boy"};
let mut list_of_structs = Structure::list_of_structs();
Structure::add_to_list_of_structs(&mut list_of_structs, structure1);
Structure::add_to_list_of_structs(& mut list_of_structs, structure2);
dbg!(list_of_structs);
}
#[derive(Debug, Clone)]
struct Structure<'a>{
num: f64,
string: &'a str,
}
impl<'a> Structure<'a>{
fn do_something(&mut self){
self.num += 1f64;
}
fn add_to_list_of_structs(list_of_structs: &mut Vec<Structure<'a>>,
structure: Structure<'a>){
list_of_structs.push(structure);
// list_of_structs.to_vec()
}
fn list_of_structs()->Vec<Structure<'a>>{
Vec::new()
}
}
The Structure::list_of_structs() method is similar to static methods in java where if Structure were a class the method would be called thus: Structure.list_of_structs()
.
I created this method because from what I have learnt, it is not possible to create a static variable such that I would refer to it thus:
Structure::list_of_structs
instead of having the vector returned via a method. Is this assumption wrong and if it is how would on go about refactoring the code?