rust - 为什么 `use std::{ self, ... };` 不编译?

标签 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 调用。以下是为什么这在 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/

相关文章:

rust - 如何在 rust 中使用 nom 解析对称带引号的字符串?

reference - 将元组引用的迭代器解压缩到两个引用集合中

rust - 如何释放由暴露在 WebAssembly 中的 Rust 代码分配的内存?

rust - % 运算符在闭包内出错

collections - 如何更新 BTreeSet 中的所有值?

assembly - 如何在(发布的)Rust版本中找到函数的汇编代码?

rust - 如何在弹出列表中启用 atom-racer 文档?

rust - 如何将 'struct' 转换为 '&[u8]' ?

rust - CSV from_writer 在 stdout() 上工作,但在 from_path 上失败

rust - 如何编写一个 fn 来处理输入并返回迭代器而不是完整结果?