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:
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![]
}
}
}
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![]
}
}
}