Skip to content

Instantly share code, notes, and snippets.

@anxiousmodernman
Created July 24, 2016 14:09
Show Gist options
  • Save anxiousmodernman/904980f00156a4c06be76f50d0be5686 to your computer and use it in GitHub Desktop.
Save anxiousmodernman/904980f00156a4c06be76f50d0be5686 to your computer and use it in GitHub Desktop.
Trouble understanding lifetimes
extern crate yaml_rust;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::process;
// NOTE: why self here, again?
// because `use` defaults from crate root, and yaml is beneath
// crate root
use self::yaml_rust::{YamlLoader, YamlEmitter, Yaml};
use self::yaml_rust::yaml;
// funky macro so you can use "{:?}" to print custom structs
#[derive(Debug)]
pub struct Config<'a> {
dirs: Vec<&'a str>,
}
pub fn read_file(filename: &str) -> Result<String, io::Error> {
let mut f = try!(File::open(filename));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
pub fn new_config<'a>(path: &str) -> Config<'a> {
let v: Vec<&'a str> = Vec::new();
//let parsed: Vec<&'a yaml_rust::Yaml>;
//let mut parsed: Vec<Yaml>;
let mut v1;
let conf;
match read_file(path) {
Ok(s) => {
let parsed = YamlLoader::load_from_str(&s).unwrap();
let dirs = parsed[0]["dirs"].as_vec().unwrap();
println!("---- dirs content: {:?}", dirs);
v1 = Vec::new();
for item in dirs {
println!("---- item content: {:?}", item);
match item.as_str() {
Some(x) => v1.push(x),
_ => println!("wtf")
}
}
conf = Config{dirs: v1.clone()};
return conf;
}
Err(error) => {
println!("{:?}", error);
process::exit(1); // reading conf failed. Bail.
}
}
//let conf: Config<'a> = Config{dirs: v};
conf
}
@anxiousmodernman
Copy link
Author

Error from cargo build

src/helpers.rs:40:24: 40:30 error: `parsed` does not live long enough
src/helpers.rs:40             let dirs = parsed[0]["dirs"].as_vec().unwrap();

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