There are several ways around it. One is to switch from a direct reference to Cell to a safe back-reference that consists of a back-pointer to the Game and an index to the vector element:struct Player<'a> { game: &'a Game, cell_idx: usize,}impl<'a> Player<'a> { pub fn new(game: &'a Game, cell_idx: usize) -> Player<'a> { Player { game, cell_idx } } pub fn current_cell_name(&self) -> &str { &self.game.cells[self.cell_idx].name }}可编译示例 at the playground/a>.Compilable example at the playground.它的缺点是不允许添加单元格,除非附加它们,因为它会使玩家的索引无效.它还需要对 Player 对单元格属性的每次访问进行边界检查.但 Rust 是一种具有引用和智能指针的系统语言——我们能做得更好吗?That has the downside that it doesn't allow adding cells except by appending them, because it would invalidate players' indices. It also requires bounds-checking on every access to a cell property by Player. But Rust is a systems language that has references and smart pointers - can we do better?另一种方法是投入一些额外的努力来确保 Cell 对象不受向量重新分配的影响.在 C++ 中,可以通过使用指向单元格的指针向量而不是单元格向量来实现这一点,而在 Rust 中,可以通过将 Box 存储在向量中来实现这一点.但这不足以满足借用检查器的要求,因为缩小或删除向量仍然会使单元格无效.The alternative is to invest a bit of additional effort to make sure that Cell objects aren't affected by vector reallocations. In C++ one would achieve that by using a vector of pointers-to-cell instead of a vector of cells, which in Rust one would use by storing Box<Cell> in the vector. But that wouldn't be enough to satisfy the borrow checker because shrinking or dropping the vector would still invalidate the cells.这可以使用引用计数指针来修复,这将允许单元格在向量增长(因为它被分配在堆上)和收缩时幸存下来,因此它不再包含它(因为它不是由向量):This can be fixed using a reference-counted pointer, which will allow the cell to both survive the vector growing (because it is allocated on the heap) and shrinking so it no longer inclues it (because it is not owned exclusively by the vector):struct Game { is_running: bool, cells: Vec<Rc<Cell>>,}impl Game { fn construct_cells() -> Vec<Rc<Cell>> { ["a", "b", "c"] .iter() .map(|n| { Rc::new(Cell { name: n.to_string(), }) }) .collect() } pub fn new() -> Game { let cells = Game::construct_cells(); Game { is_running: false, cells, } } // we could also have methods that remove cells, etc. fn add_cell(&mut self, cell: Cell) { self.cells.push(Rc::new(cell)); }}以每个 Cell 的额外分配(以及从 Game 到每个单元格的额外指针取消引用)为代价,这允许实现 Player 比索引更高效:At the cost of an additional allocation for each Cell (and an additional pointer dereference from Game to each cell), this allows an implementation of Player more efficient than index:struct Player { cell: Rc<Cell>,}impl Player { pub fn new(cell: &Rc<Cell>) -> Player { Player { cell: Rc::clone(cell), } } pub fn current_cell_name(&self) -> &str { &self.cell.name }}再次,可编译示例 游乐场. 这篇关于对向量中元素的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-02 16:44