相关疑难解决方法(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万
查看次数

我如何解析JSON文件?

到目前为止,我的目标是在Rust中解析此JSON数据:

extern crate rustc_serialize;
use rustc_serialize::json::Json;
use std::fs::File;
use std::io::copy;
use std::io::stdout;

fn main() {
    let mut file = File::open("text.json").unwrap();
    let mut stdout = stdout();
    let mut str = &copy(&mut file, &mut stdout).unwrap().to_string();
    let data = Json::from_str(str).unwrap();
}
Run Code Online (Sandbox Code Playgroud)

并且text.json

{
    "FirstName": "John",
    "LastName": "Doe",
    "Age": 43,
    "Address": {
        "Street": "Downing Street 10",
        "City": "London",
        "Country": "Great Britain"
    },
    "PhoneNumbers": [
        "+44 1234567",
        "+44 2345678"
    ]
}
Run Code Online (Sandbox Code Playgroud)

解析它的下一步应该是什么?我的主要目标是获取这样的JSON数据,并从中解析一个密钥,如Age.

json rust

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

将 TOML 反序列化为具有值的枚举向量

我正在尝试读取 TOML 文件以创建一个结构,该结构包含具有关联值的枚举向量。这是示例代码:

extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate toml;

use std::fs::File;
use std::io::Read;

#[derive(Debug, Deserialize, PartialEq)]
struct Actor {
    name: String,
    actions: Vec<Actions>,
}

#[derive(Debug, Deserialize, PartialEq)]
enum Actions {
    Wait(usize),
    Move { x: usize, y: usize },
}

fn main() {
    let input_file = "./sample_actor.toml";
    let mut file = File::open(input_file).unwrap();
    let mut file_content = String::new();
    let _bytes_read = file.read_to_string(&mut file_content).unwrap();
    let actor: Actor = toml::from_str(&file_content).unwrap();
    println!("Read actor {:?}", actor);
}
Run Code Online (Sandbox Code Playgroud)

Cargo.toml

[dependencies]
serde_derive = "1.0.10" …
Run Code Online (Sandbox Code Playgroud)

rust toml serde

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

标签 统计

rust ×3

file-io ×1

json ×1

serde ×1

toml ×1