Created
November 14, 2014 13:50
-
-
Save gchp/bf19636bdfe1eb3e39d7 to your computer and use it in GitHub Desktop.
Does not live long enough
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::cell::RefCell; | |
use std::io::{BufferedReader, File}; | |
struct Buffer<'b> { | |
lines: Vec<RefCell<Line>>, | |
cursor: Cursor<'b>, | |
} | |
impl<'b> Buffer<'b> { | |
fn new() -> Buffer<'b> { | |
Buffer { | |
lines: Vec::new(), | |
cursor: Cursor::new() | |
} | |
} | |
fn new_from_file(path: &Path) -> Buffer<'b> { | |
let mut file = BufferedReader::new(File::open(path)); | |
let mut buffer = Buffer::new(); | |
for line in file.lines() { | |
let data = line.unwrap(); | |
buffer.lines.push(RefCell::new(Line::new_from_string(data))); | |
} | |
buffer.cursor.line = Some(&buffer.lines[0]); | |
buffer | |
} | |
} | |
struct Line { | |
data: String, | |
} | |
impl Line { | |
fn new_from_string(data: String) -> Line { | |
Line { | |
data: data, | |
} | |
} | |
} | |
struct Cursor<'c> { | |
line: Option<&'c RefCell<Line>>, | |
} | |
impl<'c> Cursor<'c> { | |
fn new() -> Cursor<'c> { | |
Cursor { | |
line: None | |
} | |
} | |
} | |
fn main() { | |
let path = Path::new("/Users/Greg/test.txt"); | |
let buffer = Buffer::new_from_file(&path); | |
} | |
/* | |
$ rustc edit.rs | |
edit.rs:27:36: 27:48 error: `buffer.lines` does not live long enough | |
edit.rs:27 buffer.cursor.line = Some(&buffer.lines[0]); | |
^~~~~~~~~~~~ | |
edit.rs:18:49: 30:6 note: reference must be valid for the lifetime 'b as defined on the block at 18:48... | |
edit.rs:18 fn new_from_file(path: &Path) -> Buffer<'b> { | |
edit.rs:19 let mut file = BufferedReader::new(File::open(path)); | |
edit.rs:20 let mut buffer = Buffer::new(); | |
edit.rs:21 | |
edit.rs:22 for line in file.lines() { | |
edit.rs:23 let data = line.unwrap(); | |
... | |
edit.rs:18:49: 30:6 note: ...but borrowed value is only valid for the block at 18:48 | |
edit.rs:18 fn new_from_file(path: &Path) -> Buffer<'b> { | |
edit.rs:19 let mut file = BufferedReader::new(File::open(path)); | |
edit.rs:20 let mut buffer = Buffer::new(); | |
edit.rs:21 | |
edit.rs:22 for line in file.lines() { | |
edit.rs:23 let data = line.unwrap(); | |
... | |
error: aborting due to previous error | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment