[Reflexion] Best pratices, design pattern, singleton, struct borrow

Hi,

I was thinking about the concept of borrow and exploit that in rust.
I have a example (that not works) to illustrate it, but to try to find a elegant way of doing that in rust.

use std::sync::Mutex;

static SINGLETON: Mutex<Vec<StructCantDeriveCopyOrClone>> = Mutex::new(vec![]);

struct StructCantDeriveCopyOrClone {
    s: String,
}

impl StructCantDeriveCopyOrClone {

    fn push_in_singleton(&self) {
        let mut s = SINGLETON.lock().unwrap();
        s.push(*self);
    }
}

fn main() {
    let my_struct = StructCantDeriveCopyOrClone { s : "Test".to_string() };

    my_struct.push_in_singleton();
}

Imagine you have a struct value (my_struct here) that will be not use anymore after...
But you want to take this struct and make it put in a vec (named SINGLETON here).
So now, this structure can be again used in the future..
Is there a way to "give ourself" to be contained in a vec in the implementation of the structure ?
This sound too much Oriented Object Programming maybe ? But I really want to borrow struct to the vec finally...

The struct must be with this String. No change to &str allowed for this example.

To transfer ownership you don't pass a reference, you pass the value. Note the change of &self to self below.

    fn push_in_singleton(self) {
        let mut s = SINGLETON.lock().unwrap();
        s.push(self);
    }

playground

After transferring ownership, you cannot use the original variable. There can only be one owner of a value. If you need to access it again, you must access it via the SINGLETON Vec.

2 Likes

Thank you very much for your time.

1 Like