Is there method to save variables into local file?

for example, I have below three variables on my rust code:

let a = vec![1,2,3,4];
let b = "abcd";
let c = 23;

I want to save these variables into my local file("/root/data/abc") for next time use;
which method is comfortable for this?

You'll have to pick a format to use when reading and writing the file.

Here's a quick example using serde and serde_json to save a JSON file

Playground

use std::fs::OpenOptions;

use serde::{Deserialize, Serialize};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let a = vec![1, 2, 3, 4];
    let b = "abcd";
    let c = 23;

    let mut file = OpenOptions::new()
        .create(true)
        .truncate(true) // If the file already exists we want to overwrite the old data
        .write(true)
        .read(true)
        .open("saved.json")?;

    serde_json::to_writer(&mut file, &Save { a, b: b.into(), c })?;

    // Read the saved data back.
    let saved: Save = serde_json::from_reader(OpenOptions::new().read(true).open("saved.json")?)?;

    println!("{saved:?}");

    Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
struct Save {
    a: Vec<i32>,
    b: String,
    c: i32,
}
4 Likes

Hi semicoleon
Thank you very much.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.