[英]Why isn't `use std::io` enough here?
I tried to compile the following program: 我试着编译以下程序:
use std::io;
fn main() {
io::stdout().write(b"Please enter your name: ");
io::stdout().flush();
}
Unfortunately, compiler resisted: 不幸的是,编译器拒绝:
error: no method named `write` found for type `std::io::Stdout` in the current scope
--> hello.rs:4:18
|
4 | io::stdout().write(b"Please enter your name: ");
| ^^^^^
|
= help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
= help: candidate #1: `use std::io::Write`
I found that I needed to do use std::io::{self, Write};
我发现我需要
use std::io::{self, Write};
. 。 What does
use std::io;
什么
use std::io;
actually do then and how do (if possible) I pull all names defined in std::io
? 实际上那么做(如果可能的话)我如何拉出
std::io
定义的所有名字? Also, would it be a bad style? 还有,这会是一种糟糕的风格吗?
What does
use std::io;
什么
use std::io;
actually do then?实际上呢?
It does what every use-statement does: makes the last part of the used path directly available (pulling it into the current namespace). 它执行每个use-statement所做的事情:使用过的路径的最后一部分直接可用(将其拉入当前命名空间)。 That means that you can write
io
and the compiler knows that you mean std::io
. 这意味着你可以编写
io
,编译器知道你的意思是std::io
。
How do I pull all names defined in
std::io
?如何提取
std::io
定义的所有名称?
With use std::io::*;
use std::io::*;
. 。 This is commonly referred to as glob-import .
这通常称为glob-import 。
Also, would it be a bad style?
还有,这会是一种糟糕的风格吗?
Yes, it would. 是的,它会的。 Usually you should avoid glob-imports.
通常你应该避免使用glob-imports。 They can be handy for certain situations, but cause a lot of trouble on most cases.
它们在某些情况下可以派上用场,但在大多数情况下会造成很多麻烦。 For example, there is also the trait
std::fmt::Write
... so importing everything from fmt
and io
would possibly result in name-clashes. 例如,还有特征
std::fmt::Write
...因此从fmt
和io
导入所有内容可能会导致名称冲突。 Rust values explicitness over implicitness, so rather avoid glob-imports. Rust重视隐含性的显式性,所以宁可避免使用glob-imports。
However, there is one type of module that is usually used with a glob-import: preludes. 但是,有一种类型的模块通常与glob-import一起使用:prelude。 And in fact, there is even a
std::io::prelude
which reexports important symbols. 事实上,甚至还有一个重新出口重要符号的
std::io::prelude
。 See the documentation for more information. 有关更多信息,请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.