Member-only story

Reading and Writing a File in Rust

This article will review how you can create, open a file, read its contents and write into it in Rust.

Mousse Anis
5 min readAug 30, 2022
Photo by Scott Graham on Unsplash

As a software engineer or someone interested in technologies, read and write (aka I/O for Input and Output) operations are some essential concepts that you should know.

After reading this article, you will be able to create, open a file, read its content, and add content to it. So let get dive in.

But first, let's lay some vital groundwork by reviewing how characters are represented in Rust.

String and str (aka string slices)

I know this title (☝🏿)seems a bit confusing … in Rust, we have two types to represent strings :

  • str: string slice, the only string type of the core Rust programing language. This type is static and immutable, and we usually see it in its borrowed form: &str.
  • String: is the second string type made available in Rust, thanks to the standard library. This type is more flexible, as it can be owned and is mutable.

Both string types are UTF-8 encoded (more on that here); String is used when you need to own or change your string and &str when you want to visualize a string.

--

--

Mousse Anis
Mousse Anis

Written by Mousse Anis

Ex Quant, now software engineer who loves to cook. Opinions/Views are my own

No responses yet