-3

How can I return the result of a File::open operation in Rust?

The compiler complains that the result is owned by the function, but provides no suggestions, and there's no useful suggestions easily searchable on the web.

Code:

use std::io::{Read, Seek};

trait ReadSeek: Read + Seek {}

fn get_file_reader(path: &'static str) ->
    Result<&mut dyn ReadSeek, Box<dyn Error>> {

    Ok(&mut File::open(path)?)
}

Error:

error[E0515]: cannot return value referencing temporary value
  --> src/archive/zipfile.rs:32:9
   |
32 |         Ok(&mut File::open(path)?)
   |         ^^^^^^^^-----------------^
   |         |       |
   |         |       temporary value created here
   |         returns a value referencing data owned by the current function
Neil
  • 24,551
  • 15
  • 60
  • 81
  • Yes, thanks @Herohtar. It looks like Google's search results are so bad, now, that you have to add `site:stackoverflow.com` to your query to avoid getting absolute shit results from Stack Overflow copypaste trash sites. – Neil Dec 29 '21 at 20:40
  • Is there a reason you are trying to return a trait object (`dyn ReadSeek`) instead of just returning `File`? – Herohtar Dec 29 '21 at 22:12

1 Answers1

3

The issue is you are returning a reference to data that is owned by your function. The solution is to not return & but the File itself, in this case a Box (owned pointer, unlike & which is a reference) because you are using a trait object (dyn).

fn get_file_reader(path: &'static str) ->
    Result<Box<dyn ReadSeek>, Box<dyn Error>> {

    let file = File::open(path)?;

    Ok(Box::new(file))
}

If you don't need the return type to use dyn you could do:

fn get_file_reader(path: &'static str) ->
    Result<File, Box<dyn Error>> {

    let file = File::open(path)?;

    Ok(file)
}