]> git.proxmox.com Git - rustc.git/blob - src/doc/book/nostarch/chapter09-read-to-string-update.md
New upstream version 1.35.0+dfsg1
[rustc.git] / src / doc / book / nostarch / chapter09-read-to-string-update.md
1 Please insert this text after the paragraph ending in “ergonomic way to write
2 it” on page 160.
3
4 ---
5
6 Speaking of different ways to write this function, Listing 9-9 shows that
7 there’s a way to make this even shorter.
8
9 Filename: src/main.rs
10
11 ```
12 use std::io;
13 use std::fs;
14
15 fn read_username_from_file() -> Result<String, io::Error> {
16 fs::read_to_string("hello.txt")
17 }
18 ```
19
20 Listing 9-9: Using `fs::read_to_string` instead of opening and then reading the
21 file
22
23 Reading a file into a string is a fairly common operation, so Rust provides the
24 convenient `fs::read_to_string` function that opens the file, creates a new
25 `String`, reads the contents of the file, puts the contents into that `String`,
26 and returns it. Of course, using `fs::read_to_string` doesn’t give us the
27 opportunity to explain all the error handling, so we did it the longer way
28 first.