Skip to content

Instantly share code, notes, and snippets.

@donabrams
Forked from anonymous/playground.rs
Last active December 22, 2015 16:33
Show Gist options
  • Save donabrams/0fe5f9f4dc871106b5c1 to your computer and use it in GitHub Desktop.
Save donabrams/0fe5f9f4dc871106b5c1 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::error::Error;
use std::mem;
use std::str;
type Something<'a> = HashMap<&'a str, &'a str>;
fn get_lines(filename: &str) -> Result<io::Lines<BufReader<File>>, io::Error> {
let mut f = try!(File::open(filename));
Ok(BufReader::new(f).lines())
}
fn get_something<'a>() -> Result<&'a Something<'a>, io::Error> {
let mut something = Something::new();
try!(get_lines("gates.txt"))
.map(|line| line.unwrap().as_ref())
.map(|line| something.insert(line, line));
Ok(&something)
}
fn main() {
match get_something() {
Ok(something) => println!("Values: (yay, {})", something.get("yay").unwrap()),
Err(e) => println!("Error: {}", e.to_string()),
}
}
@donabrams
Copy link
Author

:22:6: 22:15 error: something does not live long enough
:22 Ok(&something)
^~~~~~~~~
:17:64: 23:2 note: reference must be valid for the lifetime 'a as defined on the block at 17:63...
:17 fn get_something<'a>() -> Result<&'a Something<'a>, io::Error> {
:18 let mut something = Something::new();
:19 try!(get_lines("gates.txt"))
:20 .map(|line| line.unwrap().as_ref())
:21 .map(|line| something.insert(line, line));
:22 Ok(&something)
...
:18:39: 23:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 18:38
:18 let mut something = Something::new();
:19 try!(get_lines("gates.txt"))
:20 .map(|line| line.unwrap().as_ref())
:21 .map(|line| something.insert(line, line));
:22 Ok(&something)
:23 }
:20:18: 20:31 error: borrowed value does not live long enough
:20 .map(|line| line.unwrap().as_ref())
^~~~~~~~~~~~~
:17:64: 23:2 note: reference must be valid for the lifetime 'a as defined on the block at 17:63...
:17 fn get_something<'a>() -> Result<&'a Something<'a>, io::Error> {
:18 let mut something = Something::new();
:19 try!(get_lines("gates.txt"))
:20 .map(|line| line.unwrap().as_ref())
:21 .map(|line| something.insert(line, line));
:22 Ok(&something)
...
:20:18: 20:40 note: ...but borrowed value is only valid for the block at 20:17
:20 .map(|line| line.unwrap().as_ref())
^~~~~~~~~~~~~~~~~~~~~~
error: aborting due to 2 previous errors
playpen: application terminated with error code 101

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment