【发布时间】:2022-08-22 00:36:54
【问题描述】:
我正在尝试在此https://github.com/dhole/rust-homework/tree/master/hw03 之后学习 rust,在此https://rust-unofficial.github.io/too-many-lists/second-option.html 之后,当我尝试这样做时:
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
left: Link<T>,
right: Link<T>,
}
pub struct BST<T: std::cmp::PartialOrd> {
root: Link<T>,
}
impl<T: std::cmp::PartialOrd> BST<T> {
pub fn new() -> Self {
BST { root: None }
}
pub fn insert(&mut self, elem: T) -> bool {
self.root.insert(elem)
}
}
trait InsertSearch<T: std::cmp::PartialOrd> {
fn insert(&mut self, elem: T) -> bool;
}
impl<T: std::cmp::PartialOrd> InsertSearch<T> for Link<T> {
fn insert(&mut self, elem: T) -> bool {
true
}
}
我收到以下 2 个错误:
error[E0308]: mismatched types
--> src\\second.rs:35:34
|
23 | impl<T: std::cmp::PartialOrd> BST<T> {
| - this type parameter
...
35 | self.root.insert(elem)
| ^^^^ expected struct `Box`, found type parameter `T`
|
= note: expected struct `Box<second::Node<T>>`
found type parameter `T`
当我打电话给Option<Box<Node<T>>>::insert(T) 时,为什么它期待一个盒子?
error[E0308]: mismatched types
--> src\\second.rs:35:17
|
28 | pub fn insert(&mut self, elem: T) -> bool {
| ---- expected `bool` because of return type
...
35 | self.root.insert(elem)
| ^^^^^^^^^^^^^^^^^^^^^^ expected `bool`, found mutable reference
|
= note: expected type `bool`
found mutable reference `&mut Box<second::Node<T>>`
而这个真的让我很困惑。当插入函数的返回类型为 bool 时,为什么会得到 &mut Box<second::Node<T>>?那我叫什么?
-
Nitpick:
PartialOrd在前奏中,你不需要完全限定它。
标签: rust