0

如何将Rust的“struct”转换为数据流?

 1 year ago
source link: https://www.jdon.com/62767
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何将Rust的“struct”转换为数据流?


当且仅当原始结构派生Serialize和Deserialize特征时,可以使用bincode将它们序列化为 binary-encoded Vec<u8>。

在这里,我用一个元组结构MyStruct包裹了原始结构StructFromAnotherTool,并使用hex将结果从Vec<u8>编码和解码为十六进制字符串,这样我就可以很容易地将十六进制字符串表示法存储在数据库中。
请注意,这些结构在最后派生出PartialEq和Debug,然后使用断言测试。

use serde::{Deserialize, Serialize};
use hex;

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct StructFromOtherTool {
    x: f32,
    y: f32,
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct MyStruct(StructFromOtherTool);

fn main() { 
    let mystruct = MyStruct(SomeStruct { x: 1.3, y: 5.2 });

let encoded: Vec<u8> = bincode::serialize(&mystruct).unwrap();

// 这个十六进制的字符串表示可以存储在数据库中。
    let s = hex::encode(encoded.clone());

println!("Hex encoded struct: {}", s);

// 然后我们对十六进制字符串进行解码,并使用bincode将其反序列化为一个MyStruct实体。
    let v = hex::decode(s).unwrap();

let decoded = bincode::deserialize(&v[..]).unwrap();

assert_eq!(mystruct, decoded);


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK