【问题标题】:thread 'main' panicked at 'Box<Any>'线程 'main' 在 'Box<Any>' 处惊慌失措
【发布时间】:2020-06-24 17:47:30
【问题描述】:

我正在尝试学习 Rust。我正在关注一本书online,它实现了unix程序cat。现在我试图读取作为cargo run file1.txt file2.txt 之类的参数传递的文件的内容,但程序出现了恐慌:

D:\rust\cat> cargo run .\src\test.txt
   Compiling cat v0.1.0 (D:\rust\cat)
    Finished dev [unoptimized + debuginfo] target(s) in 0.62s
     Running `target\debug\cat.exe .\src\test.txt`
thread 'main' panicked at 'Box<Any>', src\main.rs:12:28

这是我的程序:

use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() > 1 {
        match read_file(&args) {
            Ok(content) => println!("{}", content),
            Err(reason) => panic!(reason),
        }
    }
}

fn read_file(filenames: &Vec<String>) -> Result<String, io::Error> {
    let mut content = String::new();

    for filename in filenames {
        let mut file = File::open(filename)?;
        file.read_to_string(&mut content)?;
    }

    Ok(content)
}

谁能解释我在这里缺少什么?

【问题讨论】:

  • 不相关,但不需要收集迭代器:play.integer32.com/…
  • 我不明白为什么会有这个消息,但你不应该自己恐慌,使用unwrap或错误传播:play.integer32.com/…
  • @Boiethios 谢谢!会尝试的。我用恐慌!正如本书使用的那样

标签: rust


【解决方案1】:

std::env::args 返回的Args 迭代器的第一个元素通常是可执行文件的路径(参见docs 了解更多详情)。

出现错误是因为您没有跳过第一个参数:程序二进制不是有效的 UTF-8 字节序列。

显然没有意义的错误thread 'main' panicked at 'Box&lt;Any&gt;' 是因为panic! 没有与相同的参数一起使用 format! 语法。

use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;

fn main() {
    for filename in env::args().skip(1) {
        match read_file(filename) {
            Ok(content) => println!("{}", content),
            Err(reason) => panic!("{}", reason),
        }
    }
}

fn read_file(filename: String) -> Result<String, io::Error> {
    let mut content = String::new();

    let mut file = File::open(filename)?;
    file.read_to_string(&mut content)?;

    Ok(content)
}

【讨论】:

  • 对,我不知道第一个参数是可执行文件本身。谢谢你指出
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2021-11-03
  • 2021-11-23
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多