简体   繁体   中英

Borrowing the T in a Rc<RefCell<T>>

I'm trying to do something like this

use std::cell::{RefCell,Ref,RefMut};
use std::rc::Rc;

struct Entity;

struct Tile {
    entity: Option<Rc<RefCell<Entity>>>
}

impl Tile {
    pub fn try_read_entity<'a>(&'a self) -> Option<Ref<'a, Entity>> {
        self.entity.map(|e| e.borrow())
    }
}

I'm getting lifetime related errors and find it difficult to understand what exactly is going wrong, or whether it's even possible to do this.

This is the signature of the Option::map() method:

fn map<U, F>(self, f: F) -> Option<U>
    where F: FnOnce(T) -> U

self means that map() takes the option by value , that is, it consumes it. In particular it means moving the option value out from its previous place. But you can't do it because in your code you take self by reference - you cannot move from out of a reference, and that's exactly what error is about.

However, you don't need to consume the option, you only need a reference to its contained value. Fortunately, Option<T> provides a method, fn as_ref(&'a self) -> Option<&'a T> , which can be used to obtain a reference to internals of an option. If you just call it prior to calling map() , your code will work:

self.entity.as_ref().map(|e| e.borrow())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM