如何将“结构"转换为“&[u8]"? [英] How to convert 'struct' to '&[u8]'?
问题描述
我想通过 TcpStream
发送我的结构.我可以发送 String
或 u8
,但我不能发送任意结构.例如:
I want to send my struct via a TcpStream
. I could send String
or u8
, but I can not send an arbitrary struct. For example:
struct MyStruct {
id: u8,
data: [u8; 1024],
}
let my_struct = MyStruct { id: 0, data: [1; 1024] };
let bytes: &[u8] = convert_struct(my_struct); // how??
tcp_stream.write(bytes);
收到数据后,我想将&[u8]
转换回MyStruct
.如何在这两种表示之间进行转换?
After receiving the data, I want to convert &[u8]
back to MyStruct
. How can I convert between these two representations?
我知道 Rust 有一个用于序列化数据的 JSON 模块,但我不想使用 JSON,因为我想发送数据尽可能快和小,所以我想没有或非常小的开销.
I know Rust has a JSON module for serializing data, but I don't want to use JSON because I want to send data as fast and small as possible, so I want to no or very small overhead.
推荐答案
(无耻地窃取并改编自 Renato Zannon 对类似问题的评论)
(Shamelessly stolen and adapted from Renato Zannon's comment on a similar question)
也许像 bincode
这样的解决方案适合您的情况?这是一个工作摘录:
Perhaps a solution like bincode
would suit your case? Here's a working excerpt:
Cargo.toml
[package]
name = "foo"
version = "0.1.0"
authors = ["An Devloper <an.devloper@example.com>"]
edition = "2018"
[dependencies]
bincode = "1.0"
serde = { version = "1.0", features = ["derive"] }
main.rs
use serde::{Deserialize, Serialize};
use std::fs::File;
#[derive(Serialize, Deserialize)]
struct A {
id: i8,
key: i16,
name: String,
values: Vec<String>,
}
fn main() {
let a = A {
id: 42,
key: 1337,
name: "Hello world".to_string(),
values: vec!["alpha".to_string(), "beta".to_string()],
};
// Encode to something implementing `Write`
let mut f = File::create("/tmp/output.bin").unwrap();
bincode::serialize_into(&mut f, &a).unwrap();
// Or just to a buffer
let bytes = bincode::serialize(&a).unwrap();
println!("{:?}", bytes);
}
然后您就可以将字节发送到任何您想要的地方.我假设您已经意识到天真地发送字节的问题(例如潜在的字节顺序问题或版本控制),但我会提及它们以防万一^_^.
You would then be able to send the bytes wherever you want. I assume you are already aware of the issues with naively sending bytes around (like potential endianness issues or versioning), but I'll mention them just in case ^_^.
这篇关于如何将“结构"转换为“&[u8]"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!