Rust:将价值从选项中移出并推入堆栈

Rust: moving value out of option and pushing onto a stack

我有一个 Option 类型的值。如果类型中有 Leg 值,我想修改 Leg 结构,然后通过将腿从当前存储在 self._current_leg 中的位置移动到已完成腿的堆栈上来将其标记为 "complete"在 self._completed_legs。然后我想将 _current_leg 值设置为 _expected_legs 堆栈中的下一条腿。但是,我在 Trip.dropoff() 中的 self._completed_legs.push(leg) 行收到类型不匹配的错误,因为堆栈需要 Leg 类型的结构,而我传递的是 &mut Leg 类型。我不知道如何将值移出 _current_leg 变量 -- 我似乎只能借用该值。

相关代码在此代码块底部。感谢您的帮助。

use std::collections;

pub struct Stack<T> {
    maxsize: usize,
    items: Vec<T>,
}

impl<T> Stack<T> {

    pub fn new(maxsize: usize) -> Self {
        Self {
            maxsize,
            items: Vec::with_capacity(maxsize),
        }
    }
    pub fn pop(&mut self) -> Option<T> {
        self.items.pop()
    }
    pub fn push(&mut self, item: T) -> bool {
        if self.items.len() == self.maxsize {
            return false;
        }
        self.items.push(item);
        return true;
    }
    pub fn size(&self) -> usize {
        self.items.len()
    }
    pub fn peek(&self) -> Option<&T> {
        self.items.last()
    }
}

pub struct Leg {
    // not important
    _trip_index: usize
}

impl Leg {
    fn dropoff(&mut self, time: i64) {

    }

    fn pickup(&mut self, time: i64) {

    }
}

pub struct Trip {
    _current_leg: Option<Leg>,
    _completed_legs: Stack<Leg>,
    _expected_legs: Stack<Leg>
}

impl Trip {

    fn dropoff(&mut self, time: i64) {
        let leg = self._current_leg.as_mut().unwrap();
        leg.dropoff(time);
        self._completed_legs.push(leg);
        self._current_leg = self._expected_legs.pop();
    }
}

您的 self._current_leg 属于 Option<Leg> 类型,但您不能拥有它,因为它是 self 的一部分。基本上就好像你有一个 &mut Option<Leg>。您不能调用 unwrap(),因为 unwrap() 取得了 Option.

的所有权

您解决了这个调用 as_mut() 但将您的 &mut Option<Leg> 转换为 Option<&mut Leg>:现在您拥有 Option 但它不包含值,只是一个参考,因此您仍然不拥有 Leg 本身。

你需要的是Option::take():

pub fn take(&mut self) -> Option<T>

它将用 None 和 return 以前的值替换给定的值。像这样的东西将在你的代码中工作:

let mut leg = self._current_leg.take().unwrap();