Push to vector in struct from function

Hello

I have a struct containing a vector. For that struct I have implemented a function 'add' which purpose is to validate if the data is valid and adds it to the struct.

pub struct MemoryData {
    cats: Vec<Cat>,
}
impl MemoryData {
    pub fn add(&mut self, cat: Cat) -> bool {
        self.cats.push(cat);
        true
    }
}

I would like to use this code like this:

//Create cat object
let cat: Cat = Cat::new(name, age, color, race);

//Save cat object
data_layer::MemoryData::add(cat);

This generates the following error:

data_layer::MemoryData::add(cat);
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 2 parameters

Because the self-parameter is not defined. A solution would be to recreate the MemoryData object over-and-over again, but that would also re-initialize the vector and make all the precedent data in the vector vanish.

How do I solve this issue?

If this is in another method of MemoryData, then you can call the add method on self, like this:

impl MemoryData {
    fn do_stuff(&mut self) {
        //Create cat object
        let cat: Cat = Cat::new(name, age, color, race);
        
        //Save cat object
        self.add(cat);
    }
}

If not, then you'll need to call it on some specific MemoryData value, like this:

foo.add(cat);  // `foo` must be a variable that refers to a `MemoryData`.

If you don't have a MemoryData value in scope, then you will need to get one somehow. You could have the caller of your function pass one in, or you could keep one in a field of a struct, or you could create a new one and store it in a local variable...

1 Like

Thanks for your reply. I have solved it by initializing MemoryData in my main and passing it on through my program through the parameters (by mutable reference).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.