Rust “使用"与 C++“使用命名空间"相比 [英] Rust "use" vs. C++ "using namespace"

查看:30
本文介绍了Rust “使用"与 C++“使用命名空间"相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rust 中声明多个使用"语句是否被认为是不好的风格?我是一名最近开始尝试 Rust 的 C++ 程序员.我在查看 Rust 代码时注意到的一件事是,在许多 Rust 程序中,程序顶部会有一堆 use 语句.来自 C++,不鼓励使用 using namespace std 尤其是在制作头文件时,但在我见过的大多数 Rust 程序中似乎并非如此.那么以下哪些琐碎的例子被认为是更好的 Rust 编程风格?如果您正在制作二进制程序与模块,它会改变吗?为什么?

Is it considered bad style to declare multiple "use" statements in Rust? I am a C++ programmer that recently began trying out Rust. One thing I've noticed as I review Rust code is that in many Rust programs there will be a bunch of use statements at the top of the program. Coming from C++, it was discouraged to use using namespace std especially when making header files, but that doesn't seem to be the case in most of the Rust programs I've seen. So which of the following trivial examples is considered to be better Rust programming style? Does it change if you're making a binary program vs. a module? And why?

use std::sync::Arc;
use std::sync::Mutex;
use std::thread::Thread;
use std::rand::random;

fn main() {
    let mut vec: Vec<char> = (0u8..10).map(|i| i as char).collect();

    let mut data = Arc::new(Mutex::new(vec));
    for i in 1usize..10 {
        let data = data.clone();
        let thread = Thread::spawn(move || {
            let mut data = match data.lock() {
                Ok(guard)   => guard,
                Err(e)      => panic!("{}, was poisoned", e)
            };
            data.push(random::<char>());
        });
    }
}

或者这个……

fn main() {
    let mut vec: Vec<char> = (0u8..10).map(|i| i as char).collect();

    let mut data = std::sync::Arc::new(
                            std::sync::Mutex::new(vec)
                                        );
    for i in 1usize..10 {
        let data = data.clone();
        let thread = std::thread::Thread::spawn(move || {
            let mut data = match data.lock() {
                Ok(guard)   => guard,
                Err(e)      => panic!("{}, was poisoned", e)
            };
            data.push(std::rand::random::<char>());
        });
    }
}

推荐答案

您可能对看起来相似的名称(useusing namespace)感到困惑.事实上,它们在语义上非常不同.

You are probably confused by the similarly looked names (use and using namespace). In fact they are very different in semantics.

using namespace 将命名空间的全部内容包含在当前作用域中,因此,例如,您可以使用 cout 代替 std::cout:

using namespace in C++ includes the whole contents of a namespace into the current scope, so, for example, you can use cout instead of std::cout:

using namespace std;

cout << "Hello!
";

然而,Rust 中的

use 仅包含指定的名称,因此您仍然需要限定您实际指的是哪个项目:

use in Rust, however, includes only the specified name, so you still have to qualify which item you are actually referring to:

use std::mem;
use std::fmt::Debug;

fn do_something<T: Debug>(t: T) { ... }

fn main() {
    let (mut x, mut y) = ...;
    mem::swap(&mut x, &mut y);
}

注意 Debug 如何在没有限定符的情况下使用,但 swap 仍然需要模块限定符,因此 Rust 中的 use 更像是 usingC++ 中的 (没有 namespace).因为 use 在它导入的内容上非常具体,所以几乎总是使用它被认为是一种很好的风格,所以你的第一个例子是惯用的.

Note how Debug is used without qualifiers but swap still requires a module qualifier, so use in Rust is more like using (without namespace) in C++. Because use is very specific in what it imports, it is considered a good style to use it almost always, so your first example is the idiomatic one.

其实 using namespace 更像是 Rust 中的 glob 导入:

In fact, using namespace is more like glob imports in Rust:

use std::*;

而且确实有点不鼓励全局导入.但是,Rust 结构约定比 C++ 使用的更灵活(特别是在 std 库中),所以 use std::* 不会给你整个标准库,只有顶部级模块.Glob 导入在其他几种情况下也很有用,例如从另一个模块重新导出名称或在一个模块中组装所有库扩展特征时.

And glob imports indeed are somewhat discouraged. However, Rust structuring conventions are more flexible that the ones used by C++ (in particular, in the std library), so use std::* won't give you the whole standard library, only the top-level modules. Glob imports are also useful in a couple of other situations, e.g. when reexporing names from another module or assembling all library extension traits in one module.

不,无论您是在编写库还是可执行文件,约定都不会改变.Rust 没有像 C/C++ 的头文件那样包含字面量,所以每个编译单元都是完全独立的,可以有任何你喜欢的导入——它不会影响它的用户(除非这些是 pub use's,当然).

And no, conventions do not change regardless of if you're writing a library or an executable. Rust does not have anything like C/C++'s headers with literal inclusions, so each compilation unit is completely independent and can have any imports you like - it won't affect its users (unless these are pub use's, of course).

这篇关于Rust “使用"与 C++“使用命名空间"相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆