rustHow to write struct to file in Rust
Writing a struct to a file in Rust is relatively straightforward. First, you need to create a File object, which can be done using the File::create
method. Then, you need to serialize the struct into a byte array, which can be done using the bincode
crate. Finally, you can write the byte array to the file using the write_all
method. An example of this process is shown below:
use std::fs::File;
use bincode::{serialize, deserialize};
#[derive(Serialize, Deserialize)]
struct MyStruct {
field1: i32,
field2: String,
}
fn main() {
let my_struct = MyStruct {
field1: 5,
field2: String::from("Hello World!"),
};
let serialized = serialize(&my_struct).unwrap();
let mut file = File::create("my_struct.bin").unwrap();
file.write_all(&serialized).unwrap();
}
The output of this code is a binary file called my_struct.bin
which contains the serialized version of the struct.
Helpful links
Related
More of Rust
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How do I create an array of strings in Rust?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to use regex captures in Rust?
- How to convert JSON to a struct in Rust?
- How to pop an element from a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...