gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:33:16 25 4
gpt4 key购买 nike

我需要像这样在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正确地做到这一点?

参见 plaground

最佳答案

给定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();
}
}

关于json - 如何在循环中将结构序列化为io::Write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60111338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com