【问题标题】:Expecting and getting different types期待和得到不同的类型
【发布时间】: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&lt;Box&lt;Node&lt;T&gt;&gt;&gt;::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 时,为什么会得到 &amp;mut Box&lt;second::Node&lt;T&gt;&gt;?那我叫什么?

  • Nitpick:PartialOrd 在前奏中,你不需要完全限定它。

标签: rust


【解决方案1】:

这两个错误的原因相同:您没有调用您定义的insert() 函数。你正在调用另一个函数。

记住Link 实际上是Option&lt;_&gt;(准确地说是Option&lt;Box&lt;Node&lt;T&gt;&gt;&gt;)。和Option has an insert() method。它需要T(不是你的TOptionT,在这种情况下是Box&lt;Node&lt;T&gt;&gt;)并产生&amp;mut T&amp;mut Box&lt;Node&lt;T&gt;&gt;)。当你调用某个方法时,如果存在一个固有方法,你总是调用它;仅当没有具有该名称的固有方法时,您才调用特征方法,但在这种情况下存在。

解决方案可以是使用通用函数调用语法 - &lt;Link&lt;T&gt; as InsertSearch&lt;T&gt;&gt;::insert(&amp;mut self.root, elem),但我建议将 Link 设为新类型结构而不是类型别名。那是,

struct Link<T>(Box<Node<T>>);

这样,您可以定义一个固有的insert() 方法,并且您不会继承Option 的方法。

【讨论】:

  • 谢谢!我应该考虑查看 Option xD 的文档
猜你喜欢
  • 2014-05-11
  • 2021-09-17
  • 2021-12-01
  • 2012-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
相关资源
最近更新 更多