使用Rust 1.11.0,我得到了错误:
error: no method named read_to_string found for type std::result::Result<std::fs::File, std::io::Error> in the current scope
当我不使用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);
}这样做很好:
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);
}但是它也给出了一个警告,所以我必须在read_to_string()之后添加另一个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);
}这里发生了什么事?
发布于 2016-09-08 07:47:35
这是因为read_to_string()是实现io::Read特性的类型可用的方法。您尝试使用它的是一个没有实现它的Result。
当您在unwrap()上调用Result<T, E>时,它会生成T --在本例中,是实现io::Read的fs::File。
在unwrap()上不调用f.read_to_string(&mut s)时收到的警告是因为它返回的类型Result<T, E>有一个属性#[must_use],这意味着它不能被丢弃;您可以执行以下"ignoring" assignment来不获取警告:
let _ = f.read_to_string(&mut s);
https://stackoverflow.com/questions/39385218
复制相似问题