How to convert 'struct' to '&[u8]'?

后端 未结 2 553
误落风尘
误落风尘 2020-11-30 10:59

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:



        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 11:38

    (Shamelessly stolen and adapted from Renato Zannon's comment on a similar question)

    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 "]
    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,
    }
    
    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 ^_^.

提交回复
热议问题