我不知道为什么这段代码不能用 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 :
On a technical level, Rust inserts
extern crate std;
into the crate root of every crate, and
use std::prelude::v1::*;
into every module.
您还可以在查看代码时看到它的实际效果 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.
}
如您所见,由于 extern crate std;
语句,std
已经在范围内。因此,再次导入它会导致此错误。
关于rust - 为什么 `use std::{ self, ... };` 不编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55312186/