I'm trying to read a file named enable.txt
that's in the same dir as my main.rs
, and my code looks like this:
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::error::Error;
fn main() {
let path = Path::new("enable.txt");
let display = path.display();
let mut file = File::open(&path);
let mut contents = String::new();
file.read_to_string(&mut contents);
println!("{}", contents);
}
When I compile it with either cargo run
or rustc src/main.rs
, I get this error message:
error: no method named `read_to_string` found for type `std::result::Result<std::fs::File, std::io::Error>` in the current scope
--> src/main.rs:10:10
|
10 | file.read_to_string(&mut contents);
| ^^^^^^^^^^^^^^
The issue is that File::open()
returns a std::result::Result<std::fs::File, std::io::Error>
which needs to be unwrapped in some way in order to access the file. The way I prefer to do this is to use expect()
like this:
...
fn main() {
...
let mut file = File::open(&path).expect("Error opening File");
...
file.read_to_string(&mut contents).expect("Unable to read to string");
...
}
This will either return the expected value or panic
with the error message provided depending on if the operation was successful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With