Using Rust 1.11.0, I get the error:
error: no method named read_to_string found for type std::result::Result<std::fs::File, std::io::Error> in the current scope
when I'm not using unwrap()
:
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut f = File::open("D:/test/rust/io.txt"); // Error thrown here
let mut s = String::new();
f.read_to_string(&mut s);
println!("{}", s);
}
This works fine:
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut f = File::open("D:/test/rust/io.txt").unwrap();
let mut s = String::new();
f.read_to_string(&mut s); // Warning thrown here
println!("{}", s);
}
But it also gives a warning so I have to add another unwrap()
after read_to_string()
:
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut f = File::open("D:/test/rust/io.txt").unwrap();
let mut s = String::new();
f.read_to_string(&mut s).unwrap(); // Notice the 2nd unwrap here
println!("{}", s);
}
What's happening here?
It's because read_to_string()
is a method available for types implementing the io::Read
trait. What you are attempting to use it on is a Result<fs::File, io::Error>
which does not implement it.
When you call unwrap()
on a Result<T, E>
, it yields T
- in this case fs::File
that does implement io::Read
.
The warning you are getting when you don't call unwrap()
on f.read_to_string(&mut s)
is because the type Result<T, E>
it returns has an attribute #[must_use]
which means that it can not just be discarded; you can perform the following "ignoring" assignment to not get the warning:
let _ = f.read_to_string(&mut s);
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