gpt4 book ai didi

rust - 为什么编译器需要那个特征提示?

转载 作者:行者123 更新时间:2023-11-29 07:55:39 24 4
gpt4 key购买 nike

我有这段代码:

pub trait MiddlewareHandler: Clone + Send {
//...probably unimportant for the question
}

#[deriving(Clone)]
pub struct Middleware {
handlers: Vec<Box<MiddlewareHandler>>
}

#[deriving(Clone)]
pub struct Server{
middleware: Middleware
}

这让编译器对我大喊大叫:

src/server.rs:20:31: 20:37 error: the type `server::Server', which does not fulfill `Send`, cannot implement this trait
src/server.rs:20 impl http::server::Server for Server {
^~~~~~
src/server.rs:20:31: 20:37 note: types implementing this trait must fulfill `Send+Sized`
src/server.rs:20 impl http::server::Server for Server {

我花了很长时间才弄清楚我必须改变 Vec<Box<MiddlewareHandler>>Vec<Box<MiddlewareHandler + Send>>这样最终的代码看起来像这样:

pub trait MiddlewareHandler: Clone + Send {
//...probably unimportant for the question
}

#[deriving(Clone)]
pub struct Middleware {
handlers: Vec<Box<MiddlewareHandler + Send>>
}

#[deriving(Clone)]
pub struct Server{
middleware: Middleware
}

代码现在可以编译了,但我完全不明白这里到底出了什么问题。为什么 +SendVec定义?我的意思是,MiddlewareHandler trait 确实已经实现了 Send + Clone .对我来说,它看起来相当多余。

有人可以与我分享他的智慧,为什么我必须这样更改代码?

最佳答案

似乎是一个错误,我提交了 #15155 .


“问题”是 Sendhttp::server::Server 的限制.定义是

pub trait Server: Send + Clone {

意味着实现者需要同时是 Clone (这很满意,因为您已经通过 Clone 实现了 #[deriving(Clone)] )和 Send .编译器自动实现 Send对于内容满足 Send 的类型(此细节将随 opt-in built-in traits 发生变化:它们也将需要显式实现),不幸的是,原始类型类似于

pub struct Middleware {
handlers: Vec<Box<Trait>>
}

没有实现 Send一般来说:编译器无法知道 Box<Trait> 中被删除的类型是Send能够,例如它可能包含 Rc ,因此转移到不同的任务是不安全的。

编译器需要知道更多的信息,也就是说,它需要保证内部类型是Send。 ,可以通过向特征对象添加更多边界来提供:Box<Trait + Send> ...

但是,在这种情况下,MiddlewareHandler trait 已经这个 Send绑定(bind)为超特征(意味着特征对象的内容必须已经满足 Send),所以编译器没有计算出 Box<MiddlewareHandler> 很奇怪是Send (因此提交错误)。

关于rust - 为什么编译器需要那个特征提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24394197/

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