DEV Community 👩‍💻👨‍💻

Cover image for Write response from a rust function to a file
Collins Ruto
Collins Ruto

Posted on

Write response from a rust function to a file

If you want to save the response from a function for later, you can use the std::fs::write function to write the response to a file on your local file system.

For example, suppose you have a Rust function named my_function that returns a String containing the response you want to save. You can use the following code to write the response to a file named response.txt:

use std::fs;

fn my_function() -> String {
    // function body goes here
}

fn main() {
    let response = my_function();

    fs::write("response.txt", response).expect("Failed to write response to file");
}

Enter fullscreen mode Exit fullscreen mode

This will create a new file named response.txt in the current directory, and write the response from the my_function function to the file. If the file already exists, it will be overwritten with the new response.

You can then use the std::fs::read_to_string function to read the saved response from the file at a later time:

use std::fs;

fn main() {
    let response = fs::read_to_string("response.txt").expect("Failed to read response from file");

    // use the response here
}

Enter fullscreen mode Exit fullscreen mode

I hope this helps! Let me know if you have any other questions.

Top comments (0)

Top 7 Badge

Earn our Top 7 Badge!

Write a post that gets featured in our weekly "must-reads" and you can earn this badge for your profile. 😎