英文:
Why does chaining methods on a TempDir cause File creation to fail?
问题
我是一名新的Rust程序员,所以如果这个问题显得愚蠢,我深感抱歉。我正在尝试理解为什么在TempDir
上链接方法会导致相同Path
上的File::create
调用失败。
我的情况是这样的:我正在编写一个小型库,用于在JSON和YAML之间进行转换,以学习这门语言。我试图编写一个测试,执行以下操作:
- 创建一个包含一些JSON编码文本的文件。
- 反序列化以确保它变成了
serde_json::Value
。
为此,我编写了以下代码:
let temp_dir_path = TempDir::new("directory").expect("无法创建目录");
let path = temp_dir_path.path().join("test-file.json");
let mut temp_file = File::create(&path).expect("无法创建文件");
writeln!(temp_file, r#"{{"key": 2}}"#).expect("写入失败");
// 有关加载文件并对其进行断言的一些内容
这个代码有效,但后来我想:“为什么不将前两行合并成一行呢?” 于是我尝试了以下代码:
let path = TempDir::new("directory")
.expect("无法创建目录")
.path()
.join("test-file.json");
let mut temp_file = File::create(&path).expect("无法创建文件");
writeln!(temp_file, r#"{{"key": 2}}"#).expect("写入失败");
这段代码会一直失败,显示"无法创建文件"的消息。但我不明白的是"为什么"。我的直觉是这两个调用应该是相同的(毕竟,我基本上只是内联了一个变量);然而,显然并非如此。在这些情况下,是否有关于expect
的某些我不理解的东西导致它无法正常工作?
英文:
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:
- Create a file with some json-encoded text
- 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?
答案1
得分: 3
tempdir::TempDir
的文档说明:> 一旦TempDir
值被丢弃,该路径上的目录将被删除,这正是在语句末尾的内联变体中发生的 temporary value。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论