Rust provides two methods for handling unrecoverable errors unwrap and expect, they can be used on both Result and Option types, they will trigger a panic! if the value is an Err(E) variant for Result<T, E> or a None variant for Option<T>
These methods extract the inner value but terminate the program if the operation fails. They are particularly useful for quick prototyping or situations where an error is truly unrecoverable.
In this challenge, you will interact with file operations to demonstrate the use of unwrap and expect. Instead of directly working with Result or Option, you will use standard library functions that return these types and handle their results using unwrap and expect.
Your Task
Implement the following functions:
read_file_to_string: This function takes a file path as input, attempts to read its contents, and returns the contents as aString. Useexpectto handle any file I/O errors with a custom error message of exactlyFailed to read file: <path>.get_env_variable: This function retrieves the value of an environment variable by name. Useunwrapto panic if the variable is not set.
Notes
expectprovides a way to add context to your panics, which can help with debugging.unwrapis more concise but less descriptive when errors occur.
Hints
If you're stuck, here are some hints to help you solve the challenge:
<details> <summary>Click here to reveal hints</summary>- Use
std::fs::read_to_string(path)to read the contents of a file. It returns aResult<String, std::io::Error>. - Use
std::env::var(key)to retrieve an environment variable. It returns aResult<String, std::env::VarError>. - Use
.expect()to add a custom error message when handling aResult. - Use
.unwrap()for a quick, less descriptive error handling method.
pub fn read_file_to_string(path: &str) -> String {// 1. Implement the function}pub fn get_env_variable(key: &str) -> String {// 2. Implement the function}/// Example usagepub fn main() {// Example 1: Using read_file_to_stringlet file_content = read_file_to_string("example.txt");println!("File content: {}", file_content);// Example 2: Using get_env_variablestd::env::set_var("EXAMPLE_KEY", "example_value");let value = get_env_variable("EXAMPLE_KEY");println!("Environment variable value: {}", value);// Must panicread_file_to_string("nonexistent.txt");get_env_variable("MISSING_KEY");}