rusttempdir

Why does chaining methods on a TempDir cause File creation to fail?


I'm a new rustecean, so I apologize if this question is silly. I'm trying to understand why chaining methods on a TempDir causes File::create calls on the same Path to fail.

My situation is this: I'm writing a small library to convert between JSON and YAML to learn the language. I'm trying to write a test which does the following:

  1. Create a file with some json-encoded text
  2. Deserialize it to ensure that it becomes a serde_json::Value

To do that, I've written the following code.

let temp_dir_path = TempDir::new("directory").expect("couldn't create directory");
let path = temp_dir.path().join("test-file.json");
let mut temp_file = File::create(&path).expect("failed to create file");
writeln!(temp_file, "{{\"key\": 2}}").expect("write failed");

// some stuff about loading the file and asserting on it

That works, but then I thought "why don't I just collapse the first two lines into one?" So I tried that and wrote the following:

let path = TempDir::new("directory")
    .expect("couldn't create directory")
    .path()
    .join("test-file.json");
let mut temp_file = File::create(&path).expect("failed to create file");
writeln!(temp_file, "{{\"key\": 2}}").expect("write failed");

This code will consistently fail with a message of "failed to create file". The thing I don't understand though is "why". My intuition is that both of these calls should be the same (after all, I basically just inlined a variable); however, that clearly isn't happening. Is there something I don't understand happening with expect here which causes it to not work in these situations?


Solution

  • Assuming you mean tempdir::TempDir the docs state:

    Once the TempDir value is dropped, the directory at the path will be deleted,

    which is exactly what happens to your temporary value in the inlined variant at the end of the statement.