rust - "the size for values of type cannot be known at compilation time"尝试从函数返回 dyn Traits 向量时

标签 rust

我有一个函数 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![]
        }
    }
}

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

关于rust - "the size for values of type cannot be known at compilation time"尝试从函数返回 dyn Traits 向量时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72446328/

相关文章:

rust - 在 Rust 中运行外部进程

generics - 无需复制的通用数学

rust - Rust可以替代C++ ADL重载函数吗?

rust - 有没有办法只在 rustdoc 验证示例时启用 Cargo 功能?

rust - 在单独的模块中使用时使用未声明的类型或模块 `std`

struct - Rust:即使使用了作用域,多次借用结构实例作为可变对象也会失败

http - 现有循环中的异步 HTTP(S) 请求

rust - UdpSocket.recv_from 失败并显示 "end of file",但我可以在 Wireshark 中看到传入的包

string - 是否有 UTF-16 字符串类型的 Rust 库? (用于编写 Javascript 解释器)

web-scraping - 使用 scraper crate 检索兄弟元素