我不知道为什么这个代码不能用Rust 1.27.0编译。
这是我的硬盘驱动器上的test.rs:
use std::{
self,
io::prelude::*,
net::{ TcpListener, TcpStream },
};
fn main() {}
尝试使用rustc test.rs
编译时的输出:
error[E0254]: the name `std` is defined multiple times
--> test.rs:2:5
|
2 | self,
| ^^^^ `std` reimported here
|
= note: `std` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
|
2 | self as other_std,
| ^^^^^^^^^^^^^^^^^
warning: unused imports: `TcpListener`, `TcpStream`, `io::prelude::*`, `self`
--> test.rs:2:5
|
2 | self,
| ^^^^
3 | io::prelude::*,
| ^^^^^^^^^^^^^^
4 | net::{TcpListener, TcpStream},
| ^^^^^^^^^^^ ^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
这在Rust 2018中运行良好。您可能只想通过将edition = "2018"
添加到Cargo.toml
或--edition=2018
到rustc
调用来更新。以下是为什么这在Rust 2015中不起作用的答案。
来自the std::prelude
documentation:
在技术层面上,Rust插入
extern crate std;
进入每个箱子的箱子根,和
use std::prelude::v1::*;
进入每个模块。
在查看代码after macro expansion时(例如通过cargo-expand
),您还可以看到实际操作。对于您的代码,结果如下:
#![feature(prelude_import)]
#![no_std]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std;
// No external crates imports or anything else.
use std::{
self,
net::{TcpListener, TcpStream},
};
fn main() {
// Empty.
}
正如您所看到的,由于std
声明,extern crate std;
已经在范围内了。因此,再次导入它会导致此错误。