gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:34:08 25 4
gpt4 key购买 nike

我是新来的 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/

25 4 0