RustBook icon indicating copy to clipboard operation
RustBook copied to clipboard

The errors about the implement of queue

Open Jia-Baos opened this issue 1 year ago • 0 comments

// queue.rs

// 队列 #[derive(Debug)] struct Queue<T> { cap: usize, // 容量 data: Vec<T>, // 数据容器 }

impl<T> Queue<T> { fn new(size: usize) -> Self { Queue { cap: size, data: Vec::with_capacity(size), } }

// 判断是否有剩余空间、有则数据加入队列
fn enqueue(&mut self, val: T) -> Result<(), String> {
    if Self::size(&self) == self.cap {
        return Err("No space available".to_string());
    }
    self.data.insert(0, val);

    Ok(())
}

fn size(&self) -> usize {
    self.data.len()
}

}


Because the function of "size(&self) " is a method belongs to one instance, so that we can't use the Self::size(&self) to obtain the size of self, the better choice is using self.size()......

Jia-Baos avatar Sep 19 '23 02:09 Jia-Baos