gpt4 book ai didi

rust - Drop 不能用于实现扩展特征的通用结构

转载 作者:行者123 更新时间:2023-11-29 08:35:59 25 4
gpt4 key购买 nike

TL;DR https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=99952dfdc8dab353992d2681de6b6f58

Full version https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=38d0c934cb7e55b868d73bd2dde94454

我不太明白为什么这不起作用:

pub trait State {}
pub trait WithFinal: State {}
pub struct Machine<T: State> {
pub state: T,
error: Option<fn(&Event, &T)>,
transition: Option<fn(&T, &T, Event)>, // fn(&current_state, &previous_state)
}

impl<T: WithFinal> Drop for Machine<T> {
fn drop(&mut self) {}
}
   Compiling scdlang v0.1.0 (/home/wildan/Projects/OSS/scdlang)
error[E0367]: The requirement `T: statechart::WithFinal` is added only by the Drop impl.
--> src/main.rs:92:5
|
92 | / impl<T: WithFinal> Drop for Machine<T> {
93 | | fn drop(&mut self) {}
94 | | }
| |_____^
|
note: The same requirement must be part of the struct/enum definition
--> src/main.rs:74:5
|
74 | / pub struct Machine<T: State> {
75 | | pub state: T,
76 | | error: Option<fn(&Event, &T)>,
77 | | transition: Option<fn(&T, &T, Event)>, // fn(&current_state, &previous_state)
78 | | }
| |_____^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0367`.
error: Could not compile `scdlang`.

To learn more, run the command again with --verbose.

我认为它应该可以工作,因为 WithFinal extend trait State

然而,这两个 impl 工作得很好:

trait DropLike {
fn drop(&mut self);
}

impl<T: WithFinal> DropLike for Machine<T> {
fn drop(&mut self) {}
}

impl<T: State> Drop for Machine<T> {
fn drop(&mut self) {}
}

最佳答案

简短的回答是您不能在专门的泛型类型上实现 Drop

你的 DropLike 特征是 like Drop,但是 Drop 是一个语言项目,并且从编译器。这意味着此错误仅适用于 Drop

来自Rustc Error Index :

This code is not legal: it is not possible to specialize Drop to a subset of implementations of a generic type. In order for this code to work, MyStruct must also require that T implements Foo.

(也可以通过 rustc --explain E0367 看到)

这是 the issue这似乎预示了这种变化。

关于rust - Drop 不能用于实现扩展特征的通用结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54505455/

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