我试着编译以下程序:
use std::io;
fn main() {
io::stdout().write(b"Please enter your name: ");
io::stdout().flush();
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,编译器拒绝:
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`
Run Code Online (Sandbox Code Playgroud)
我发现我需要这样做use std::io::{self, Write};.那么use std::io;实际做了什么以及如何(如果可能的话)我拉出所有定义的名字std::io?还有,这会是一种糟糕的风格吗?
Luk*_*odt 11
那
use std::io;实际上做了什么?
它执行每个use-statement所做的事情:使用过的路径的最后一部分直接可用(将其拉入当前命名空间).这意味着您可以编写io并且编译器知道您的意思std::io.
如何拉出定义的所有名称
std::io?
随着use std::io::*;.这通常称为glob-import.
还有,这会是一种糟糕的风格吗?
是的,它会的.通常你应该避免使用glob-imports.它们在某些情况下可以派上用场,但在大多数情况下会造成很多麻烦.例如,还有特征std::fmt::Write......所以从中导入所有内容fmt并io可能导致名称冲突.Rust重视隐含性的显式性,所以宁可避免使用glob-imports.
但是,有一种类型的模块通常与glob-import一起使用:prelude.事实上,甚至还有一个重新出现std::io::prelude重要符号的东西.有关更多信息,请参阅文档.
| 归档时间: |
|
| 查看次数: |
268 次 |
| 最近记录: |