I want to serialize a struct, print it to standard output, read it from another program and deserialize. I found that I could use the serde crate and Bincode as the data format.
I came up with this example:
#[macro_use]
extern crate serde;
use bincode::{deserialize, serialize};
#[derive(Serialize, Deserialize)]
struct Entity {
x: f32,
y: f32,
}
#[derive(Serialize, Deserialize)]
struct World(Vec<Entity>);
fn main() {
let world = World(vec![Entity { x: 0.0, y: 4.0 }, Entity { x: 10.0, y: 20.5 }]);
let encoded: Vec<u8> = serialize(&world).unwrap();
println!("{:?}", encoded);
let decoded: World = deserialize(&encoded[..]).unwrap();
}
In Cargo.toml
I have:
[package]
name = "test"
version = "0.1.0"
edition = "2018"
[dependencies]
bincode = "1.1.4"
serde = { version = "1.0", features = ["derive"] }
But the thing that confuses me is that even I have declared to use edition = "2018"
and from my understanding, that means that extern crate serde;
could be omitted, If I remove the lines:
#[macro_use]
extern crate serde;
I get multiple errors like:
error: cannot find derive macro `Deserialize` in this scope
--> src/main.rs:3:21
|
3 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
error: cannot find derive macro `Serialize` in this scope
--> src/main.rs:3:10
|
3 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^
error: cannot find derive macro `Deserialize` in this scope
--> src/main.rs:9:21
|
9 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
error: cannot find derive macro `Serialize` in this scope
--> src/main.rs:9:10
|
9 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^
Therefore wondering when or how to use edition = "2018"
The use of #[macro_use]
makes me remember decorators from Python, could it be that same logic applies in Rust or there is work in progress to standardize more the language so that probably in an edition = "20XX
the #[macro_use]
will not be required?
#[macro_use]
extern crate serde;
I'm using Rust 1.35.0.