温馨提示:本文翻译自stackoverflow.com,查看原文请点击:json - How to serialise structs into io::Write in a loop
json rust serde stream streaming

json - 如何在循环中将结构序列化为io :: Write

发布于 2020-04-24 14:35:33

我需要像这样在Rust中进行简单的读取/处理/写入:

#[derive(serde::Deserialize)]
struct Incoming {
    first: String,
    last: String,
}

#[derive(serde::Serialize)]
struct Outgoing {
    name: String,
}

// Keep the read/write traits as generic as possible
fn stream_things<R: std::io::Read, W: std::io::Write>(reader: R, writer: W) {
    let incoming: Vec<Incoming> = serde_json::from_reader(reader).unwrap();

    for a in incoming {
        let b = Outgoing {
            name: format!("{} {}", a.first, a.last),
        };
        serde_json::to_writer(writer, &b).unwrap();
    }
}

fn main() {
    stream_things(std::io::stdin(), std::io::stdout());
}

这不能编译,因为:

error[E0382]: use of moved value: `writer`
  --> src/main.rs:20:31
   |
13 | fn stream_things<R: std::io::Read, W: std::io::Write>(reader: R, writer: W) {
   |                                    --                            ------ move occurs because `writer` has type `W`, which does not implement the `Copy` trait
   |                                    |
   |                                    help: consider further restricting this bound: `W: Copy +`
...
20 |         serde_json::to_writer(writer, &b).unwrap();
   |                               ^^^^^^ value moved here, in previous iteration of loop

std::io::Write循环写入的正确方法是什么还有如何用serde正确地做到这一点to_writer

看到的地方

查看更多

提问者
Dmytrii Nagirniak
被浏览
36
edwardw 2020-02-07 19:22

给定Wio::Write,则&mut W还为io::Write

impl<'_, W: Write + ?Sized> Write for &'_ mut W

因此以下编译:

fn stream_things<R: std::io::Read, W: std::io::Write>(reader: R, mut writer: W) {
    let incoming: Vec<Incoming> = serde_json::from_reader(reader).unwrap();

    for a in incoming {
        let b = Outgoing {
            name: format!("{} {}", a.first, a.last),
        };
        serde_json::to_writer(&mut writer, &b).unwrap();
    }
}