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

问题描述 投票:1回答:1

我不知道为什么这个代码不能用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
1个回答
5
投票

这在Rust 2018中运行良好。您可能只想通过将edition = "2018"添加到Cargo.toml--edition=2018rustc调用来更新。以下是为什么这在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;已经在范围内了。因此,再次导入它会导致此错误。

© www.soinside.com 2019 - 2024. All rights reserved.