为什么不使用 std::{ self, ... };'编译?

  • 本文关键字:编译 self std rust
  • 更新时间 :
  • 英文 :


我不知道为什么不能使用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 Invocation。以下是为什么它在Rust 2015中不起作用的答案。


来自std::prelude文档:

在技术层面上,生锈插入

extern crate std;

进入每个板条箱的板条箱根,

use std::prelude::v1::*;

进入每个模块。

您还可以在宏扩展后查看代码时(例如,通过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已经处于范围。因此,将其导入另一个时间会导致此错误。

最新更新