【问题标题】:Result<usize, std::io::error::Error> does not implement expect in Rust 1.0.0Result<usize, std::io::error::Error> 在 Rust 1.0.0 中没有实现期望
【发布时间】:2016-09-22 20:13:30
【问题描述】:

在“猜谜游戏”教程示例 (here) 中,我的编译器给出了以下错误,我将其解释为 expect 不存在于 read_lineResult 上。

error: type `core::result::Result<usize, std::io::error::Error>` does not implement any method in scope named `expect`

违规代码:

use std::io;

fn main() {
    println!("**********************");
    println!("***Guess the number***");
    println!("**********************");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line"); //<<-- error on this line
    //let guess_result=io::stdin().read_line(&mut guess);

    println!("You guessed: {}", guess);
    // println!("Result: {}", guess_result.is_ok());
}

我可以删除带有.expect() 的行并使用上面注释的行并使其正常工作。我担心的是,io::stdin().read_line 的结果类型似乎是 core::result::Result,而不是教程中提到的 std::io::Result

如果我在 Rust 操场上运行相同的代码,它似乎运行良好,所以它可能在我的环境中,但我想不出它会是什么。

其他可能相关的信息:

  • 我使用了一个重新签署 SSL 证书的公司代理,因此 rust-lang 网站推荐的安装脚本不起作用
  • 我使用rust-1.0.0-x86_64-pc-windows-gnu.msi安装
  • 我正在使用上述“1.0.0”安装程序中包含的货物
  • 我已经手动将 rustc 和 cargo 的路径添加到我的环境 PATH
  • 我在 64 位 Windows 7 上使用 cygwin

TL;DR

我需要进行哪些更改才能在我的环境中编译 expect() 行?

【问题讨论】:

标签: rust


【解决方案1】:

Rust 1.0 于 2015 年 5 月 15 日发布,一年多前。虽然 Rust 1.x 旨在向后兼容(在 Rust 1.x 上编写的代码应该适用于 Rust 1.(x+1)),但它确实旨在向前兼容性(在 Rust 1.x 上编写的代码应该适用于 Rust 1.(x-1))。

如果您仅限于 Rust 1.0,那么阅读 Rust 1.11(当前版本)的文档并不是最有用的。

您的最佳赌注是update to the newest version of Rust

话虽如此,documentation for Rust 1.0 is available online(我认为您在本地也安装了它的副本)。查看the guessing game,我们看到:

io::stdin()
    .read_line(&mut guess)
    .ok()
    .expect("Failed to read line");

也就是说,我们将Result 转换为Option。查看Result in 1.0.0 的API,我们可以看到它确实没有expect 方法。

如果你查看current docs for Result::expect,你可以看到它是在 Rust 1.4 中引入的。

【讨论】:

  • 啊哈。我现在正在拉下最新版本;谢谢!现在我想知道我从哪里得到这个到版本 1.0.0 的链接;当我回溯我的步骤时,我找不到它。
【解决方案2】:

Result&lt;T, E&gt;expect() 方法仅在 Rust 1.4.0 (source) 中引入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多