0

I cannot figure out why the following will not compile:

use std::cell::{RefCell, Ref};
use std::slice::Iter;

struct Vector {
    data: RefCell<Vec<f64>>,
}

impl Vector {
    pub fn new(data: Vec<f64>) -> Self {
        Vector {data: RefCell::new(data)}
    }

    pub fn get_data(&self) -> Ref<Vec<f64>> {
        self.data.borrow()
    }

    pub fn iter(&self) -> Iter<f64> {
        self.get_data().iter()
        // Fails with `self.get_data()` does not live long enough
    }
}

fn main() {
}

playground

The full error is:

rustc 1.16.0 (30cf806ef 2017-03-10)
error: borrowed value does not live long enough
  --> <anon>:18:9
   |
18 |         self.get_data().iter()
   |         ^^^^^^^^^^^^^^^ does not live long enough
19 |         // Fails with `self.get_data()` does not live long enough
20 |     }
   |     - temporary value only lives until here
   |
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 17:36...
  --> <anon>:17:37
   |
17 |       pub fn iter(&self) -> Iter<f64> {
   |  _____________________________________^ starting here...
18 | |         self.get_data().iter()
19 | |         // Fails with `self.get_data()` does not live long enough
20 | |     }
   | |_____^ ...ending here

error: aborting due to previous error
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
dillonh2
  • 155
  • 2
  • 12
  • Have you already seen [Returning the T borrowed from RefCell](http://stackoverflow.com/q/30281664/155423)? – Shepmaster Apr 12 '17 at 19:45
  • I have, but I cannot figure out how to properly apply that to my situation. I tried to define `data` at `RefCell>>`, but how will I get an `Iter` out of that? @Shepmaster – dillonh2 Apr 12 '17 at 19:53

0 Answers0