我正在尝试将一些外部 GLSL 代码读取到 Rust 中。 读取工作正常,但我在最终表达式中遇到了终身问题(在 Ok(_) 分支中)
错误:s
寿命不够长
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,
}
}
一旦函数结束("s"超出范围),绑定到"s"的字符串将被释放,因此您无法返回对函数外部其内容的引用。最好的方法是返回字符串本身:
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,
}
}