Rust 中的文件计数

我有这个 python 代码,我正在尝试用 rust 重新创建它:

filecount = 0
while True:
    with open(f"file{filecount}.txt", "w") as file:
        file.write("Hello World")
        file.close()
        filecount += 1

在 Rust 中,我尝试了这个,但是在编译时我得到了一些关于 enum 错误的信息。

use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut filecount = 0;
    while True {
        let mut file = File::create("file{}.txt", filecount)?;
        file.write_all(b"Hello, world!")?;
        Ok(())
    }
}

prog-fh

一一查看错误信息即可。

True存在于 Python 中,但 Rust 期望true顺便说一句,在 Rust 中,无限循环是loop { ... }. 你忘了自增filecounta for(无限与否)可以解决这个问题。

您正在使用文件名create()作为格式化操作。你应该let name = format!("file{}.txt", filecount);在打电话之前做好准备create()

Ok(())你写的应该是代表整个函数的返回值(一旦循环完成),但你把它的循环中。然后在这个函数的末尾()隐式返回,与预期的结果类型不匹配。

这是调整代码示例的最小尝试。

use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    // count from 0 to infinity,  0..5 would be more reasonable
    for filecount in 0.. {
        let name = format!("file{}.txt", filecount);
        let mut file = File::create(name)?;
        file.write_all(b"Hello, world!")?;
        if filecount > 4 {
            // I don't want to fill up my filesystem but your
            // original example creates an infinite number of files
            break;
        }
    }
    Ok(()) // return success at the end of the loop
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章