I have a struct that is used by different functions. Instead of passing the struct as input to the different functions, I think I can implement the struct with all the functions that need to access it. However, there are certain fixed basic functions that I want to provide so that whenever the struct is created, I don't have to implement the same set of functions over and over again.
Put in another way, what I really want is the struct inheritance: I have certain set of methods associated with struct
and user can add their custom functions to struct
and allow them to access the data contained in data. Is there anyway able to do so?
Concretely, suppose I have a struct called AppContext
and the fixed set of functions are new
and bdev_name
:
pub struct AppContext {
bdev: *mut raw::spdk_bdev,
bdev_desc: *mut raw::spdk_bdev_desc,
bdev_io_channel: *mut raw::spdk_io_channel,
buff: *mut c_char,
bdev_name: *const c_char,
}
impl AppContext {
pub fn new() -> Self {
let context: AppContext;
unsafe {
context = mem::uninitialized();
}
context
}
pub fn bdev_name(&mut self, name: &str) {
self.bdev_name = CString::new(name)
.expect("Couldn't create a string")
.into_raw()
}
}
Now, when I use this struct, I do:
let mut context = AppContext::new();
context.bdev_name("Nvme0n1");
I want to add one extra function (say end()
) that can work on the data within the context struct. However, end()
is very domain specific function and needed in a specific module, and thus it's not a good idea to implement as part of the context struct.
Is there any way I can workaround the issue (i.e. add custom function to predefined struct
)?