Passing different structs to a function

I have two structs that should be send via my websocket from server to client.

This function sends the Data struct.

static DATA: Lazy<Mutex<Data>> = Lazy::new( || Mutex::new(Data::default()));

pub fn set_data(data: Data) {
    *DATA.lock().unwrap() = data;
}

How can I change this function to not only send Data but also Modules.

Your function doesn't send anything through websocket as-is. It stores its argument in a global variable.

Are you asking whether there are generic statics? If so, then the answer is "no".

2 Likes

Maybe create an enum like:

enum MyEnum {
    DataValue(Data),
    ModulesValue(Modules)
}

Then, if you have a variable of type MyEnum, you can set it either to MyEnum::DataValue wrapping a Data struct, or to MyEnum::ModulesValue wrapping a Modules struct.

Example:

static VARIABLE: Mutex<Option<MyEnum>> = Mutex::new(None);

pub fn set_data(data: Data) {
    VARIABLE.lock().unwrap().replace(MyEnum::DataValue(data));
}

pub fn set_modules(modules: Modules) {
    VARIABLE.lock().unwrap().replace(MyEnum::ModulesValue(modules));
}
5 Likes

This is a good idea, thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.