更新时间:2022-11-05 23:04:47
让我们看看你的错误信息:
Let's look at your error message:
error[E0599]: 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:11:14
|
11 | file.read_to_string(&mut s);
| ^^^^^^^^^^^^^^ method not found in `std::result::Result<std::fs::File, std::io::Error>`
错误消息几乎就是它在罐头上所说的 - 类型 Result
确实没有方法read_to_string
.这实际上是 一个关于 trait Read的方法代码>
.
The error message is pretty much what it says on the tin - the type Result
does not have the method read_to_string
. That's actually a method on the trait Read
.
你有一个 Result
因为 File::open(&path)
可以失败.失败用 Result
类型表示.Result
可以是 Ok
,这是成功案例,或者是 Err
,失败案例.
You have a Result
because File::open(&path)
can fail. Failure is represented with the Result
type. A Result
may be either an Ok
, which is the success case, or an Err
, the failure case.
您需要以某种方式处理失败情况.最简单的方法是使用 expect
:
You need to handle the failure case somehow. The easiest is to just die on failure, using expect
:
let mut file = File::open(&path).expect("Unable to open");
您还需要将 Read
带入范围才能访问 read_to_string
:
You'll also need to bring Read
into scope to have access to read_to_string
:
use std::io::Read;
我强烈推荐通读Rust 编程语言 并执行示例.带有Result的可恢复错误
一章代码> 将是高度相关的.我认为这些文档是一流的!
I'd highly recommend reading through The Rust Programming Language and working the examples. The chapter Recoverable Errors with Result
will be highly relevant. I think these docs are top-notch!