相关疑难解决方法(0)

什么是在Rust 1.x中读取和写入文件的事实上的方法?

由于Rust比较新,我看到了很多阅读和编写文件的方法.许多人为他们的博客提出了非常混乱的片段,我发现的99%的例子(即使在Stack Overflow上)来自不稳定的构建,不再有效.现在Rust是稳定的,什么是简单,可读,非恐慌的读取或写入文件片段?

这是我最接近阅读文本文件的东西,但它仍然没有编译,即使我很确定我已经包含了我应该拥有的一切.这是基于我在所有地方的Google+上发现的一个片段,我唯一改变的是旧BufferedReader的现在只是BufReader:

use std::fs::File;
use std::io::BufReader;
use std::path::Path;

fn main() {
    let path = Path::new("./textfile");
    let mut file = BufReader::new(File::open(&path));
    for line in file.lines() {
        println!("{}", line);
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨:

error: the trait bound `std::result::Result<std::fs::File, std::io::Error>: std::io::Read` is not satisfied [--explain E0277]
 --> src/main.rs:7:20
  |>
7 |>     let mut file = BufReader::new(File::open(&path));
  |>                    ^^^^^^^^^^^^^^
note: required by `std::io::BufReader::new`

error: no method named `lines` found for type `std::io::BufReader<std::result::Result<std::fs::File, std::io::Error>>` in the current scope
 --> src/main.rs:8:22
  |> …
Run Code Online (Sandbox Code Playgroud)

file-io rust

107
推荐指数
3
解决办法
3万
查看次数

在Rust中逐行读取大文件

我的Rust程序旨在逐行读取非常大(最多几GB)的简单文本文件.问题是,此文件太大而无法立即读取,或将所有行传输到a Vec<String>.

在Rust中处理这个问题的惯用方法是什么?

rust

13
推荐指数
1
解决办法
1万
查看次数

为什么 rust 的 read_line 函数使用可变引用而不是返回值?

考虑这段代码来读取 rust 中的用户输入

use std::io;
fn main() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("error: unable to read user input");
    println!("{}", input);
}
Run Code Online (Sandbox Code Playgroud)

为什么没有办法这样做?

use std::io;
fn main() {
    let mut input = io::stdin()
        .read_line()
        .expect("error: unable to read user input");
    println!("{}", input);
}
Run Code Online (Sandbox Code Playgroud)

其他语言会更方便

rust

5
推荐指数
1
解决办法
303
查看次数

标签 统计

rust ×3

file-io ×1