A cleaner way to get the contents of a file as a string in Rust?

Like my first immersion in Rust after a while, I started writing code to upload the contents of the file to a string, for further processing (now I just print it)

Is there a cleaner way to do this than I am now? It seems like I need to be too detailed, but I don't see any good ways to clean it.

use std::io; use std::io::File; use std::os; use std::str; fn main() { println!("meh"); let filename = &os::args()[1]; let contents = match File::open(&Path::new(filename)).read_to_end() { Ok(s) => str::from_utf8(s.as_slice()).expect("this shouldn't happen").to_string(), Err(e) => "".to_string(), }; println!("ugh {}", contents.to_string()); } 
+6
source share
1 answer

Read::read_to_string is the shortest I know about:

 use std::io::prelude::*; use std::fs::File; fn main() { let mut file = File::open("/etc/hosts").expect("Unable to open the file"); let mut contents = String::new(); file.read_to_string(&mut contents).expect("Unable to read the file"); println!("{}", contents); } 

Thinking about failures is what Rust likes to place in the front and center.

+13
source

Source: https://habr.com/ru/post/979589/


All Articles