1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2024-12-14 22:15:54 +02:00

Simplify error handling pages (#851)

This makes the `use` statements more consistent and shortens some
variable names.
This commit is contained in:
Martin Geisler 2023-06-22 16:27:06 +02:00 committed by GitHub
parent ccde0db38c
commit aba7fd7f56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 8 additions and 8 deletions

View File

@ -17,7 +17,7 @@ enum ReadUsernameError {
}
fn read_username(path: &str) -> Result<String, ReadUsernameError> {
let mut username = String::with_capacity(100);
let mut username = String::new();
fs::File::open(path)?.read_to_string(&mut username)?;
if username.is_empty() {
return Err(ReadUsernameError::EmptyUsername(String::from(path)));

View File

@ -4,7 +4,7 @@ Sometimes we want to allow any type of error to be returned without writing our
all the different possibilities. `std::error::Error` makes this easy.
```rust,editable,compile_fail
use std::fs::{self, File};
use std::fs;
use std::io::Read;
use thiserror::Error;
use std::error::Error;
@ -14,8 +14,8 @@ use std::error::Error;
struct EmptyUsernameError(String);
fn read_username(path: &str) -> Result<String, Box<dyn Error>> {
let mut username = String::with_capacity(100);
File::open(path)?.read_to_string(&mut username)?;
let mut username = String::new();
fs::File::open(path)?.read_to_string(&mut username)?;
if username.is_empty() {
return Err(EmptyUsernameError(String::from(path)).into());
}

View File

@ -4,11 +4,11 @@ We have already seen the `Result` enum. This is used pervasively when errors are
expected as part of normal operation:
```rust,editable
use std::fs::File;
use std::fs;
use std::io::Read;
fn main() {
let file = File::open("diary.txt");
let file = fs::File::open("diary.txt");
match file {
Ok(mut file) => {
let mut contents = String::new();

View File

@ -19,8 +19,8 @@ some_expression?
We can use this to simplify our error handing code:
```rust,editable
use std::fs;
use std::io::{self, Read};
use std::{fs, io};
use std::io::Read;
fn read_username(path: &str) -> Result<String, io::Error> {
let username_file_result = fs::File::open(path);