Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust. "the size for values of type cannot be known at compilation time" when try to return dynamic vector from function

I have a function Processor::process which can return dynamic vector of functions. When I try to use it I got an error:

error[E0277]: the size for values of type (dyn FnMut(String, Option<Vec<u8>>) -> Option<u8> + 'static) cannot be known at compilation time

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fn handler1(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

fn handler2(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

fn handler3(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

struct Processor {}
impl Processor {
    pub fn process(data: u8) -> Vec<dyn FnMut(String, Option<Vec<u8>>) -> Option<u8>> {
        return match data {
            1 => vec![handler1],
            2 => vec![handler1, handler2],
            3 => vec![handler1, handler2, handler3],
            _ => {}
        }
    }
}

This is minimal sandbox implementation.

Could you please help to set correct typing for function return ?

>Solution :

Either you box them, or you return a reference with an specific lifetime. In this case ‘static:

fn handler1(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

fn handler2(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

fn handler3(a: String, b: Option<Vec<u8>>) -> Option<u8> {
    None
}

struct Processor {}
impl Processor {
    pub fn process(data: u8) -> Vec<&'static dyn FnMut(String, Option<Vec<u8>>) -> Option<u8>> {
        return match data {
            1 => vec![&handler1],
            2 => vec![&handler1, &handler2],
            3 => vec![&handler1, &handler2, &handler3],
            _ => vec![]
        }
    }
}

Playground

You can also just use function pointers instead of the trait dynamic dispatch:

impl Processor {
    pub fn process(data: u8) -> Vec<fn(String, Option<Vec<u8>>) -> Option<u8>> {
        return match data {
            1 => vec![handler1],
            2 => vec![handler1, handler2],
            3 => vec![handler1, handler2, handler3],
            _ => vec![]
        }
    }
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading