Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save structured data to file?

Tags:

rust

My program contains a huge precomputation with constant output. I would like to avoid running this precomputation in the next times I run the program. Thus, I'd like to save its output to file in the first run of the program, and just load it the next time I run the program.

The output contains non-common data types, object and structs I defined myself.

How do I go about doing that?

like image 268
Snoop Catt Avatar asked Mar 10 '26 23:03

Snoop Catt


1 Answers

A de-facto standard way for (de-)serializing rust objects is serde. Given a rust struct (or enum) it produces an intermediate representation, which then can be converted to a desired format (e.g. json). Given a struct:

use serde::{Serialize, Deserialize};

// here the "magic" conversion is generated
#[derive(Debug, Serialize, Deserialize)]
struct T {
    i: i32,
    f: f64,
}

you can get a json representation with simple as oneliner:

let t = T { i: 1, f: 321.456 };
println!("{}", serde_json::to_string(&t).unwrap());
// prints `{"i":1,"f":321.456}`

as well as converting back:

let t: T = serde_json::from_str(r#"{"i":1,"f":321.456}"#).unwrap();
println!("i: {}, f: {}", t.i, t.f);
// prints i: 1, f: 321.456

Here is a playground link. This is an example for serde_json usage, but you may find other more suitable libraries like serde_cbor, serde_yaml, bincode, serde_xml and many many others.

like image 131
Kitsu Avatar answered Mar 12 '26 15:03

Kitsu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!