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

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

问题描述

在Rust中声明多个使用"语句是否被认为是不好的风格?我是最近开始尝试Rust的C ++程序员.我在查看Rust代码时注意到的一件事是,在许多Rust程序中,程序顶部都会有一堆use语句.不推荐使用using namespace std,它来自C ++,尤其是在创建头文件时,但是在我所见过的大多数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!\n";

但是,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更像是C ++中的using(没有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).

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).

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

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