Error: cannot return value referencing temporary value

For the below function I always get the bellow error. Can't figure out why the "let fp" statement is referencing a temp value. Can someone help me with the obvious I'm probably missing. I'm still learning Rust so appreciate any and all help.

This function is basically taking a file that is a symlink and returning the absolute path of the file the symlink points to.

fn get_link_info(file_path: &'static std::path::Path) -> std::io::Result<(&'static std::path::Path)> {
        let fp = fs::canonicalize(fs::read_link(file_path)?.as_path())?.to_owned().as_ref();

error: cannot return value referencing temporary value
label: temporary value created here

thanks all

as_ref is returning a reference to an object owned by the function scope, which will be dropped at the end of the function - you can't return a reference to it because there is no lifetime for a reference that can extend past the end of the function. fs::canonicalize returns a PathBuf, so there's no need to return a reference; the function could be corrected & simplified to

use std::{fs, io, path};

fn get_link_info(file_path: &path::Path) -> io::Result<path::PathBuf> {
1 Like


Was confused on ref lifetime's. Have more to add to that function but now I understand.

A bit more for understanding.

When you see something 'static, it means that the value will exist until the program termination. That could be in two cases:

  • either the value is calculated at compile-time and stored in the binary,
  • or you've explicitly leaked the memory (by Box::into_raw or similar) and are managing it yourself.

In any other case, the value will live only as long as it is bounded to something, and so any references to it must be dropped earlier then the value itself.