use*_*985 9 error-handling rust
use std::{env, fs::File, path::Path};
fn main() {
let args: Vec<_> = env::args().collect();
let pattern = &args[1];
if let Some(a) = env::args().nth(2) {
let path = Path::new(&a);
let mut file = File::open(&path);
let mut s = String::new();
file.read_to_string(&mut s);
println!("{:?}", s);
} else {
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我得到了这样的消息:
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);
| ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
She*_*ter 24
让我们看看你的错误信息:
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);
| ^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
该错误消息是差不多就是它在锡说-类型Result并没有有法read_to_string.这实际上是一种特质方法Read.
你有一个Result因为File::open(&path)可能会失败.失败用Result类型表示.A Result可以是a Ok,这是成功案例,也可以是a ,Err失败案例.
你需要以某种方式处理失败案例.最简单的方法是在失败时死亡,使用expect:
let mut file = File::open(&path).expect("Unable to open");
Run Code Online (Sandbox Code Playgroud)
您还需要Read进入范围才能访问read_to_string:
use std::io::Read;
Run Code Online (Sandbox Code Playgroud)
我强烈建议您阅读Rust编程语言并阅读示例." 可恢复错误Result "一章将具有高度相关性.我认为这些文档是一流的!
| 归档时间: |
|
| 查看次数: |
6073 次 |
| 最近记录: |