简体   繁体   English

在Rust中推荐使用`use`声明的地方在哪里?

[英]Where is the recommended place to put `use` declarations in Rust?

Where is the recommended place to put use declarations? 推荐use声明的地方在哪里? I couldn't find any decisive answer in the book, in FAQs, mailing lists or online forums. 我在书中,常见问题解答,邮件列表或在线论坛中找不到任何决定性的答案。 I'm beginning a new project in Rust and I'd prefer to get the right approach right away. 我正在Rust开始一个新项目,我宁愿立刻采取正确的方法。

Is one of the two below approaches recommended? 建议使用以下两种方法之一吗? Is it only for "aliasing" stuff or does it do more, like initialize a module if it hasn't been used before? 它只是用于“别名”的东西还是它做的更多,比如如果之前没有使用过初始化模块?

use std::io;
use std::io::Write;

fn some_func() -> () {
    [...] // We assume we need std::io here
}

fn some_other_func() -> () {
    [...] // We assume we need std::io and std::io::Write here
}

OR 要么

fn some_func() -> () {
    use std::io;
    [...] // We assume we need std::io here
}

fn some_other_func() -> () {
    use std::io;
    use std::io::Write;
    [...] // We assume we need std::io and std::io::Write here
}

TL;DR: Like almost every other piece of software, it depends on what you are doing. TL; DR:像几乎所有其他软件一样,它取决于你在做什么。 The common style that I have observed (and prefer myself) is to put them at the top of the file and only moving them to narrower scope as needed. 我观察到的(并且更喜欢自己)的常见风格是将它们放在文件的顶部,并且只根据需要将它们移动到更窄的范围。


Generally, I recommend starting by placing use statements directly after any extern crate and mod statements, separated by a blank line: 一般来说,我建议首先在任何extern cratemod语句之后直接放置use语句,用空行分隔:

extern crate foo;
extern crate bar;

mod interesting;

use std::collections::HashMap;
use foo::Foo;
use bar::{Quux, moo};    
use interesting::something;    

// structs, functions, etc.

I base this default on the fact that — most times — an import is used in multiple top-level items. 我将此默认值基于以下事实 - 大多数情况下 - 导入用于多个顶级项目。 Thus, it makes sense to only import it once. 因此,仅导入一次是有意义的。

There are times where imported traits have conflicting methods , and in those cases I scope the import to where it's needed. 有时导入的特征具有冲突的方法 ,在这种情况下,我将导入范围限定在需要的位置。 There are also cases where I'm heavily dealing with a single enum and wish to glob-import it to avoid re-stating the enum's name: 在某些情况下,我正在处理单个枚举,并希望对其进行全局导入以避免重新声明枚举的名称:

fn foo(e: MyEnum) {
    use MyEnum::*;

    match e {
        One => 1,
        Two => 2,
    }
}

In certain cases, conflicting use statements indicate that you are attempting too much in a single file and it should be split into separate files and then the use statements are no longer ambiguous. 在某些情况下,冲突的use语句表明您在单个文件中尝试过多,并且应该将其拆分为单独的文件,然后use语句不再含糊不清。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM