【问题标题】:Why is the `std` module undeclared? [duplicate]为什么“std”模块未声明? [复制]
【发布时间】:2016-04-07 21:45:37
【问题描述】:

我正在尝试从 stdin 读取单个字符,但无法正常工作。在不同的程序中,我使用了完全相同的方法,并且成功了。

let mut buffer = [0];
let _ = std::io::stdin().read(&mut buffer);
let a = buffer[0];

编译它会出现这个错误:

src/befunge.rs:220:17: 220:31 error: failed to resolve. Use of undeclared type or module `std::io` [E0433]
src/befunge.rs:220      let _ = std::io::stdin().read(&mut buffer);

【问题讨论】:

  • 在 SO 上提问时,请尽可能提供MCVE,以便客观检查答案以解决问题。例如,这可能是this simple program

标签: rust


【解决方案1】:

我假设 befunge.rs 不是你的 crate 根,而是一个子模块。在 use ...; 声明之外使用的像 std::io::stdin() 这样的路径是相对于当前模块的,而不是绝对的。为了使路径成为绝对路径,前缀 ::(就像 unix 路径中的前缀 /)-> ::std::io::stdin()。或者,您可以use 路径的某些部分,例如:

use std;
std::io::stdin();

use std::io;
io::stdin();

如果您在模块中多次使用子路径,例如std::io,通常最好在顶部使用use

如果你在 crate 根目录下,::stdstd 没有区别,因为相对查找路径是根目录。它只在子模块中很重要。另外:use 声明中的路径总是绝对的——使它们相对于当前模块前缀 self::

【讨论】:

  • 我有一个新问题,这些解决方案无法解决。我编辑了主帖。
  • 每个 SO 线程只问一个问题。所以理论上你应该为你的编辑创建一个单独的问题。但是:这个问题已经在 SO 上得到了回答,所以最好搜索一下。剧透:只需阅读编译器的整个错误消息(包括注释)。
  • 我们是否有理由让“使用”不同,这是绝对的,而不是相对于当前模块?
猜你喜欢
  • 2012-11-16
  • 2019-11-15
  • 1970-01-01
  • 2016-04-10
  • 2016-08-21
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 2014-06-19
相关资源
最近更新 更多