3
\$\begingroup\$

I've just started to teach myself Rust. I've written the following code to read a text file and store the contents in a String. Is this the typical way of doing this? Can anyone suggest any improvements to this?

use std::fs::File;
use std::io::Read;
use std::io;
fn main() {
 let file_name = "test.txt";
 let mut file_contents = String::new();
 match get_file_contents(file_name, &mut file_contents) {
 Ok(()) => (),
 Err(err) => panic!("{}", err)
 };
 println!("{}", file_contents);
}
fn get_file_contents(name: &str, mut contents: &mut String) -> Result<(), io::Error> {
 let mut f = try!(File::open(name));
 try!(f.read_to_string(&mut contents));
 Ok(())
}
chicks
2,8593 gold badges18 silver badges30 bronze badges
asked Jul 2, 2016 at 18:28
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

You could return the string directly:

fn main() {
 let file_name = "test.txt";
 let file_contents = match get_file_contents(file_name) {
 Ok(s) => s,
 Err(err) => panic!("{}", err)
 };
 println!("{}", file_contents);
}
fn get_file_contents(name: &str) -> Result<String, io::Error> {
 let mut f = try!(File::open(name));
 let mut contents = String::new();
 try!(f.read_to_string(&mut contents));
 Ok(contents)
}

and unwrap if you don’t intend to handle the error usefully:

let file_contents = get_file_contents(file_name).unwrap();
answered Jul 2, 2016 at 19:21
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.