Playback speed
×
Share post
Share post at current time
0:00
/
0:00
Transcript

Handling Errors and Files in Rust

This was bad but the docs say it'll get better.

Git repo: https://github.com/caveofprogramming/rust

See also: https://github.com/caveofprogramming/rust/blob/main/019-Extra/files/src/main.rs

Panic

The panic! macro causes the program to terminate with an error.

The error looks like this:

However, if I set the RUST_BACKTRACE environment variable to 1 in my shell, I get this:

Opening and Creating Files in Rust

We can open a file in Rust like this:

If this file doesn’t exist, we get the following output from the println!:

To create a file, we can do this:

This produces the following output:

In both cases, an enum of type Result is returned. This has two fields: Ok, and Err.

The following code tries to open a file, returns the file handle if it succeeds, and panics if it doesn’t.

In the case of an error, we can interrogate the type of error by checking the error value using the associated kind() function.

We need the following imports:

This code then checks the kind of error if the file can’t be opened:

In the case the file isn’t found, we can try to create the file.

This code produces the following output:

Thanks for reading! Subscribe for free to receive new posts and support my work.

Discussion about this podcast

John Purcell
John Purcell
Authors
John Purcell
Recent Posts