I'm writing a program in Rust that involves sending data through a TCP Connection. I cannot figure out the way to convert a struct into a byte array and back. Other solutions have only managed to convert it into u8, but as I'm new-ish to Rust (only 3 months) I cannot figure it out. I hope you guys could give a way to do it.
Asked
Active
Viewed 2,162 times
2
Ibraheem Ahmed
- 8,130
- 1
- 27
- 37
Oishik Das
- 21
- 3
-
bincode is what you seek, or msgpack – Stargateur Apr 02 '21 at 17:40
1 Answers
4
You can use bincode to transform structs into bytes and vice versa. It is built on top of the serde framework:
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Entity {
x: f32,
y: f32,
}
fn main() {
let entity = Entity { x: 1.5, y: 1.5 };
let encoded: Vec<u8> = bincode::serialize(&entity).unwrap();
let decoded: Entity = bincode::deserialize(&encoded[..]).unwrap();
}
Ibraheem Ahmed
- 8,130
- 1
- 27
- 37