"the size for values of type cannot be known at compilation time" 尝试从函数中 return 向量的 dyn Traits

"the size for values of type cannot be known at compilation time" when trying to return vector of dyn Traits from function

我有一个函数 Processor::process 可以 return 函数的动态向量。当我尝试使用它时出现错误:

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

你能帮忙设置函数 return 的正确输入吗?

box 他们,或者你 return 具有特定生命周期的 reference。在这种情况下 '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

你也可以只使用函数指针而不是 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![]
        }
    }
}

Playground