rust - Rust泛型: expected type parameter,找到&T

标签 rust ownership

我是新来的 rust ,只是涉足。
我正在尝试实现通用队列,没有生产原因,只是熟悉该语言。
我有:

pub struct Queue<T> {
    container: Vec<T>,
}

impl<T> Queue<T> {
    pub fn new() -> Self {
        Queue {
            container: Vec::new(),
        }
    }

    pub fn enqueue(&mut self, item: T) {
        self.container.push(item);
    }

    pub fn next(&mut self) -> Option<T> {
        if self.container.is_empty() {
            return None;
        } else {
            let result = self.container.first();
            self.container.remove(0);
            return result;
        }
    }
}
我收到以下错误:
error[E0308]: mismatched types
  --> src/lib.rs:22:20
   |
5  | impl<T> Queue<T> {
   |      - this type parameter
...
16 |     pub fn next(&mut self) -> Option<T> {
   |                               --------- expected `std::option::Option<T>` because of return type
...
22 |             return result;
   |                    ^^^^^^ expected type parameter `T`, found `&T`
   |
   = note: expected enum `std::option::Option<T>`
              found enum `std::option::Option<&T>`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
据我了解,这里的问题是first()返回的内容是对包含向量中的值的引用,而不是获取该值的副本。但是,我不太清楚如何从向量中获取任意项,然后从next()函数返回它。

最佳答案

Rust集合通常使您拥有从其中删除的元素的所有权。这是 Vec::remove 的情况:

pub fn remove(&mut self, index: usize) -> T

Removes and returns the element at position index within the vector, shifting all elements after it to the left.


(重点是我的)
这意味着您可以执行以下操作:
pub fn next(&mut self) -> Option<T> {
    if self.container.is_empty() {
        None
    } else {
        Some(self.container.remove(0))
    }
}
您还应该考虑使用 VecDeque ,它似乎更适合您的情况,并且具有 pop_front 可以完全满足您的需求。

关于rust - Rust泛型: expected type parameter,找到&T,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62535149/

相关文章:

rust - 在 Rust 中使用引用和使用拥有的值有区别吗?

multithreading - 在将包含Arc的self移到新线程中时,为什么会出现 “Sync is not satisfied”错误?

multithreading - 一个可变借用和多个不可变借用

rust - 如何返回 Arc<Vec<u8>> 作为 super 响应?

rust - 什么时候临时销毁?

rust - 当所有权从盒子中转移出来时,内存中会发生什么?

Rust 借用/所有权

string - 如何在 Rust 中创建固定大小的可变堆栈分配字符串?

macos - 如何将 Rust 应用程序从 macOS x86 交叉编译到 macOS Silicon?

string - 为什么从标准输入读取用户输入时我的字符串不匹配?