我有一个函数 Processor::process
它可以返回函数的动态向量。当我尝试使用它时出现错误:
error[E0277]: the size for values of type
(dyn FnMut(String, Option<Vec<u8>>) -> Option<u8> + 'static)
cannot be known at compilation time
这是我的代码:
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],
_ => {}
}
}
}
这是 minimal sandbox implementation .
你能帮忙设置函数返回的正确类型吗?
最佳答案
要么您将它们框,要么您返回具有特定生命周期的引用。在这种情况下 '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![]
}
}
}
你也可以只使用函数指针而不是 trait 动态调度:
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![]
}
}
}
关于rust - "the size for values of type cannot be known at compilation time"尝试从函数返回 dyn Traits 向量时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72446328/