rustHow to convert Rust bytes to a struct?
To convert Rust bytes to a struct, you can use the from_slice
method from the std::convert::TryFrom
trait. This method takes a slice of bytes and attempts to convert it into a struct.
Example code
use std::convert::TryFrom;
#[derive(Debug)]
struct MyStruct {
a: u8,
b: u16,
c: u32,
}
fn main() {
let bytes = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
let my_struct = MyStruct::try_from(&bytes[..]).unwrap();
println!("{:?}", my_struct);
}
Output example
MyStruct { a: 1, b: 515, c: 12845056 }
Code explanation
#[derive(Debug)]
: This attribute is used to enable theDebug
trait for theMyStruct
struct, which allows it to be printed with theprintln!
macro.MyStruct::try_from(&bytes[..])
: This method call attempts to convert the slice of bytes into an instance of theMyStruct
struct.unwrap()
: This method call is used to unwrap theResult
returned by thetry_from
method, which will either contain the converted struct or an error.println!("{:?}", my_struct)
: This macro call prints theMyStruct
instance to the console.
Helpful links
Related
More of Rust
- Hashshet example in Rust
- How to use a custom hash function with a Rust HashMap?
- How to modify an existing entry in a Rust HashMap?
- How to parse JSON string in Rust?
- How to build a Rust HashMap from an iterator?
- How to convert the keys of a Rust HashMap to a vector?
- Example of Box Rust HashMap
- How to yield return in Rust?
- How to create a generator iterator in Rust?
- How to convert a Rust slice to a fixed array?
See more codes...