io - Rust: Lifetime of String from file -
this question has answer here:
- return local string slice (&str) 1 answer
i'm trying read in external glsl code rust. reading works properly, run lifetime issue in final expression (in ok(_) branch)
error: s
not live long enough
fn read_shader_code(string_path: &str) -> &str { let path = path::new(string_path); let display = path.display(); let mut file = match file::open(&path) { err(why) => panic!("couldn't open {}: {}", display, error::description(&why)), ok(file) => file, }; let mut s = string::new(); match file.read_to_string(&mut s) { err(why) => panic!("couldn't read {}: {}", display, error::description(&why)), ok(_) => &s, } }
the string bound "s" deallocated once function ends ("s" goes out of scope), cannot return reference contents outside function. best way return string itself:
fn read_shader_code(string_path: &str) -> string { let path = path::new(string_path); let display = path.display(); let mut file = match file::open(&path) { err(why) => panic!("couldn't open {}: {}", display, error::description(&why)), ok(file) => file, }; let mut s = string::new(); match file.read_to_string(&mut s) { err(why) => panic!("couldn't read {}: {}", display, error::description(&why)), ok(_) => s, } }
Comments
Post a Comment