Rust:文件中字符串的生命周期

Rust: Lifetime of String from file

我正在尝试将一些外部 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" 的字符串将被释放,因此您不能 return 在函数外部引用其内容。 最好的方法是 return 字符串本身:

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,
    }
}