[英]Why do I need to implement MyTrait<T> instead of MyTrait<TypeA> and MyTrait<TypeB>?
我编写了一个简单的 state 机器:
struct Response {}
struct PlayResponse(Response);
struct DescribeResponse(Response);
struct EventError;
#[derive(Debug, Clone)]
pub(crate) struct RtspMachine {
state: RtspState,
}
#[derive(Debug, Clone)]
enum RtspState {
Init,
Ready,
}
trait OnEvent<T> {
fn on_event(
&mut self,
event: &T,
rtsp_machine: &mut RtspMachine,
) -> std::result::Result<Self, ()>
where
Self: Sized;
}
impl OnEvent<PlayResponse> for RtspState {
fn on_event(
&mut self,
event: &PlayResponse,
rtsp_machine: &mut RtspMachine,
) -> std::result::Result<Self, ()> {
match self {
RtspState::Init => Ok(RtspState::Ready),
RtspState::Ready => Ok(RtspState::Ready),
}
}
}
impl OnEvent<DescribeResponse> for RtspState {
fn on_event(
&mut self,
event: &DescribeResponse,
rtsp_machine: &mut RtspMachine,
) -> std::result::Result<Self, ()> {
match self {
RtspState::Init => Ok(RtspState::Ready),
RtspState::Ready => Ok(RtspState::Ready),
}
}
}
impl RtspMachine {
pub fn begin() -> RtspMachine {
RtspMachine {
state: RtspState::Init,
}
}
fn event<T>(&mut self, event: &T) -> std::result::Result<(), EventError> {
match self.state.on_event(event, self) {
Ok(_) => Ok(()),
Err(()) => Err(EventError {}),
}
}
}
但我明白了
error[E0277]: the trait bound `RtspState: OnEvent<T>` is not satisfied
--> src/lib.rs:62:26
|
62 | match self.state.on_event(event, self) {
| ^^^^^^^^ the trait `OnEvent<T>` is not implemented for `RtspState`
我有点明白为什么。 我需要做一个巨大的实现:
impl OnEvent<T> for RtspState {
fn on_event(
&mut self,
event: &T,
rtsp_machine: &mut RtspMachine,
) -> std::result::Result<Self, ()> {
match self {
RtspState::Init => Ok(RtspState::Ready),
RtspState::Ready => Ok(RtspState::Ready),
}
}
}
但这会使实施规模太大。 我很高兴在T
的不同情况下打破它。 为什么我不能在 Rust 中执行此操作? 还有其他方法吗?
如果我没记错的话,我可以在 C++ 中实现特定类型而不是泛型T
您收到此错误是因为就您的代码当前而言,Rust 不知道对 self.state.on_event 的调用是否对self.state.on_event
中指示的任何类型T
有效fn event<T>(&mut self, event: &T) -> std::result::Result<(), EventError>
。 对于所有 Rust 都知道,类型T
可以是任何东西,而RtspState::on_event
仅具有类型T
是PlayResponse
或DescribeResponse
的实现。 实际上,编译器通过错误消息告诉您这一点, the trait bound `RtspState: OnEvent<T>` is not satisfied
。 您可以向 Rust 指示 function event
仅在RtspState::on_event
对T
具有有效实现的情况下才有效,方法是在返回类型之后和左大括号之前添加where RtspState: OnEvent<T>
:
fn event<T>(&mut self, event: &T) -> std::result::Result<(), EventError>
where
RtspState: OnEvent<T>,
{
有关完整代码,您可以访问这个游乐场。
编辑:请注意,playground 链接将无法编译,但除了一般错误之外,还有其他不同的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.