尝试从函数返回 dyn Traits 向量时,“在编译时无法知道类型值的大小”

Ser*_*zzo 5 rust

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

(dyn FnMut(String, Option<Vec<u8>>) -> Option<u8> + 'static)错误[E0277]:编译时无法知道类型值的大小

这是我的代码:

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],
            _ => {}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是最小的沙箱实现

您能帮忙设置函数返回的正确输入吗?

Net*_*ave 4

要么将它们装箱,要么返回具有特定生命周期的引用。在这种情况下“静态”:

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![]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

您还可以只使用函数指针而不是特征动态调度:

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![]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

操场