Default function pointer

I have a struct with a field that is a function pointer. This function pointer takes in a generic of one type, and outputs a generic of another. I want to implement Default for this struct, which means I need to specify a default function pointer. How can I return an instance of the generic that the function pointer is supposed to return? Is there a way to just set the function pointer to empty?

Here's my current code:

pub struct Dataloader<T: Serialize + DeserializeOwned, D> {
    path: String,
    start_index: usize,
    end_index: usize,
    chunk_size: usize,
    chunks_processed: Vec<bool>,
    pre_buffer: Vec<T>,
    post_buffer: Vec<D>,
    loading_function: fn(&T) -> D,
    current_index: usize,

impl <T: Serialize + DeserializeOwned, D> Default for Dataloader<T, D> {
    fn default() -> Self {
        Dataloader {
            path: String::new(),
            start_index: 0,
            end_index: 0,
            chunk_size: 0,
            loading_function: |_| { D needs to be returned here! },
            current_index: 0,
            chunks_processed: vec![],
            pre_buffer: vec![],
            post_buffer: vec![],

What would be the best way to do this?

How about wrapping it in Option ?


You can also use a function that panics instead of returning, like this:

loading_function: |_| { unimplemented!() },

Or, if you add a D: Default bound, you could return that:

loading_function: |_| { Default::default() },
1 Like

I don't know why I forgot the unimplemented macro, exactly what I needed!

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.