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 6,145 times
4

Ibraheem Ahmed
- 11,652
- 2
- 48
- 54

Oishik Das
- 41
- 1
- 3
-
bincode is what you seek, or msgpack – Stargateur Apr 02 '21 at 17:40
1 Answers
7
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
- 11,652
- 2
- 48
- 54