gpt4 book ai didi

file-io - 从文件读取时类型推导错误

转载 作者:行者123 更新时间:2023-11-29 08:23:46 31 4
gpt4 key购买 nike

根据 multiple sources ,我相信这是从文件中读取字符串的正确方法:

use std::error::Error;

fn main() {
let path = std::path::Path::new("input.txt");

let file = match std::fs::File::open(&path) {
Err(e) => {
panic!("Failed to read file {}: {}",
path.display(),
e.description())
}
};

let mut s = String::new();
let mut v = Vec::new();
match file.read_to_string(&mut s) {
Err(e) => panic!("Failed to read file contents: {}", e.description()),
}

println!("{}", s);
}

但是这段代码在使用 Rust 1.17.0 时会产生错误,所以我一定遗漏了一些东西:

error: the type of this value must be known in this context
--> src/main.rs:16:11
|
16 | match file.read_to_string(&mut s) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^

最佳答案

您有多个重叠问题。每当调试一个编程问题时,它有助于创建一个 Minimal, Complete Verifiable Example .

首先注释掉 match file.read_to_string(&mut s) {/* ... */}。然后你会得到另一个错误:

error[E0282]: type annotations needed
--> src/main.rs:15:17
|
15 | let mut v = Vec::new();
| ----- ^^^^^^^^ cannot infer type for `T`
| |
| consider giving `v` a type

也注释掉该行,给出:

error[E0004]: non-exhaustive patterns: `Ok(_)` not covered
--> src/main.rs:6:22
|
6 | let file = match std::fs::File::open(&path) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ pattern `Ok(_)` not covered

这才是真正的问题。 Result是一个具有两个值的枚举,OkErr。您必须处理一场比赛中的所有变体。

在这种情况下,最简单的方法是使用unwrap_or_else:

let file = std::fs::File::open("input.txt").unwrap_or_else(|e| {
panic!(
"Failed to read file {}: {}",
path.display(),
e.description()
)
});

您可以删除未使用的向量并将相同的 unwrap_or_else 应用于其他失败案例。然后您需要:

  1. 导入 std::io::Read
  2. 文件声明为可变的。

您还可以:

  1. 使用 {} 直接打印错误。
  2. 将字符串切片传递给 File::open
use std::io::Read;

fn main() {
let path = "input.txt";
let mut file = std::fs::File::open(path).unwrap_or_else(|e| {
panic!("Failed to read file {}: {}", path, e);
});

let mut s = String::new();
file.read_to_string(&mut s).unwrap_or_else(|e| {
panic!("Failed to read file contents: {}", e);
});

println!("{}", s);
}

将您的代码与 What's the de-facto way of reading and writing files in Rust 1.x? 进行比较

关于file-io - 从文件读取时类型推导错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43878672/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com