0

I'am implementing doubly linked list to learn rust.
To get doubly linked list value,
I would like to return reference to value.

If I just return value, I can.
But if I do so, list value must implemeted Clone trait...
How should I do?

This is my sample code.

use std::rc::Rc;
use std::cell::RefCell;

struct Person{
    age: Rc<RefCell<i32>>,
}

impl Person {
    fn get_string<'a>(&'a self) -> &'a i32{
        //  acutually do while loop until reach designated index
        let person_age = *self.age.borrow_mut();
        //  I want to return reference to i32
        &person_age
    }
}
fn main() {
    let age = Rc::new(RefCell::new(10));
    let person = Person{age:Rc::clone(&age)};
    println!("person name is {}", person.get_string());
}
yohei
  • 9
  • 2

1 Answers1

1

You should return Ref as RefCell do

    fn get_string(&self) -> Ref<i32>{
        return self.age.borrow_mut()
    }

It should behave more or less like reference except the fact that it implements Drop. It used in RefCell instead of references because it do work to uphold RefCell invariants so while you are using RefCell, you should use it.