Here's some simple code that seems like it should work:
use serde_json;
use std::io::Write;
fn test(writer: &mut dyn Write) {
serde_json::to_writer(writer, "test1").unwrap();
serde_json::to_writer(writer, "test2").unwrap();
}
But it produces the following error:
error[E0382]: use of moved value: `writer`
--> src/main.rs:35:27
|
33 | fn test(writer: &mut dyn Write) {
| ------ move occurs because `writer` has type `&mut dyn std::io::Write`, which does not implement the `Copy` trait
34 | serde_json::to_writer(writer, "test1").unwrap();
| ------ value moved here
35 | serde_json::to_writer(writer, "test2").unwrap();
| ^^^^^^ value used here after move
To get it to work, I have to jump through this hoop:
fn test(writer: &mut dyn Write) {
serde_json::to_writer(&mut *writer, "test1").unwrap();
serde_json::to_writer(writer, "test2").unwrap();
}
What is going on here? Why can I "manually" copy the ref by deref/re-referencing it, but it doesn't implement Copy?
This is specifically something to do with the generic type signature of serde_json::to_writer
, because it also works fine with a different function:
fn test(x: &mut dyn Write) {
x.write_all(b"test1").unwrap();
x.write_all(b"test2").unwrap();
}