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
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to replace a capture group using Rust regex?
- How to use enum as hashmap key in Rust
- How to match whitespace with a regex in Rust?
- How to match a URL with a regex in Rust?
- How to get all matches from a Rust regex?
- How to read binary file in Rust
- How to replace all matches using Rust regex?
- How to use non-capturing groups in Rust regex?
See more codes...