< 返回版块

GUO 发表于 2024-04-29 09:05

Tags:泛型

代码在这里 https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=38d0795fca8ce4a67dad3b8a883858f4

编译老是报错误,不知道哪里写得不对

   Compiling playground v0.0.1 (/playground)
error[E0367]: `Drop` impl requires `T: ListEntry` but the struct it is implemented for does not
   --> src/main.rs:109:8
    |
109 |     T: ListEntry,
    |        ^^^^^^^^^
    |
note: the implementor must specify the same requirement
   --> src/main.rs:54:1
    |
54  | pub struct ListHead<T> {
    | ^^^^^^^^^^^^^^^^^^^^^^

For more information about this error, try `rustc --explain E0367`.
error: could not compile `playground` (bin "playground") due to 1 previous error

评论区

写评论
作者 GUO 2024-04-29 13:41

嗯,找到原因了,声明struct的时候也要加上 ListEntry 约束

修改前

// T 没有 ListEntry 约束,编译出错
pub struct ListHead<T> {
    head: Box<ListNode>, // 链表头
    len: usize,          // 链表长度
    _marker: PhantomData<T>,
}

修改后

// 编译成功
pub struct ListHead<T: ListEntry> {
    head: Box<ListNode>, // 链表头
    len: usize,          // 链表长度
    _marker: PhantomData<T>,
}

--
👇
wjdq: 应该是你的 ListHead 里面的 T 不能保证都是 ListEntry

https://stackoverflow.com/questions/73598836/how-to-implement-drop-on-a-generic-struct-where-t-itself-implements-a-type

wjdq 2024-04-29 09:20

应该是你的 ListHead 里面的 T 不能保证都是 ListEntry

https://stackoverflow.com/questions/73598836/how-to-implement-drop-on-a-generic-struct-where-t-itself-implements-a-type

1 共 2 条评论, 1 页