gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:29:02 26 4
gpt4 key购买 nike

我有一个函数 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com