如何访问结构中的结构字段?

Ale*_*man -1 rust

我有一个Children 的struct容器和一个pop()删除最后添加的方法Child并返回它的a值:

struct Child {
    a: i32,
    b: String,
}

struct Container<'a> {
    vector: &'a mut Vec<Child>,
}

impl<'a> Container<'a> {
    fn pop(&mut self) -> i32 {
        return self.vector.pop().a;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在编译期间收到错误:

error: no field `a` on type `std::option::Option<Child>`
  --> src/main.rs:12:34
   |
12 |         return self.vector.pop().a;
   |                                  ^
Run Code Online (Sandbox Code Playgroud)

难道范围Containerpop()不允许访问到它的价值 Child仁的范围是什么?

小智 6

Vec::pop返回一个Option<Child>,而不是一个Child.这允许它有一些合理的返回,以防止Vec弹出的元素.为了得到a可能在里面,你可以转换Option<Child>Child使用unwrap(),但这将导致你的程序如果是空的恐慌Vec.代码看起来像这样:

fn pop(&mut self) -> i32 {
    return self.vector.pop().unwrap().a;
}
Run Code Online (Sandbox Code Playgroud)

另一个选择是更密切地复制Vec行为,并None在没有元素的情况下返回.你可以使用Option' map方法:

fn pop(&mut self) -> Option<i32> {
    return self.vector.pop().map(|child| child.a)
}
Run Code Online (Sandbox Code Playgroud)