为什么不使用unwrap()导致错误?

kos*_*nix 4 types rust

使用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);
}
Run Code Online (Sandbox Code Playgroud)

这很好用:

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);
}
Run Code Online (Sandbox Code Playgroud)

不过这也给了一个警告,所以我得再添unwrap()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);
}
Run Code Online (Sandbox Code Playgroud)

这里发生了什么事?

lje*_*drz 9

这是因为read_to_string()可用于实现io::Read特征的类型的方法.你试图使用它的是一个Result<fs::File, io::Error>没有实现它的东西.

当你打电话unwrap()给a时Result<T, E>,它会产生T- 在这种情况下fs::File确实会实现io::Read.

你得到时,你不打电话报警unwrap()f.read_to_string(&mut s)是,因为类型Result<T, E>返回有一个属性#[must_use],这意味着它不能只是被丢弃; 您可以执行以下"忽略"分配以获取警告:

let _ = f.read_to_string(&mut s);

  • 另外,我建议阅读Rust书的["错误处理"一章](https://doc.rust-lang.org/book/error-handling.html)来理解*为什么*这就是这种方式它是. (4认同)