简体   繁体   English

何时在导入中使用 crate:: vs proj_name::?

[英]When to use crate:: vs proj_name:: in imports?

I understand that one can import functionality within the project in 3 different ways:我知道可以通过 3 种不同的方式在项目中导入功能:

  1. Using project name使用项目名称
use proj_name::mod1::mod2::fn_name;
  1. Using crate使用crate
use crate::mod1::mod2::fn_name;
  1. Using a relative path使用相对路径
use mod1::mod2::fn_name;

What I'm confused about is that it seems that sometimes the compiler wants me to use (1) and sometimes (2) / (3).我感到困惑的是,有时编译器似乎希望我使用(1),有时是(2)/(3)。 I can't figure out the ruleset for which should be used when.我不知道什么时候应该使用的规则集。 Can someone help?有人可以帮忙吗?

Only the crate itself is allowed to refer to itself as The crate .只有 crate 本身被允许将自己称为 The crate Every single dependant uses its name prefix.每个依赖项都使用其名称前缀。 That includes binary targets within the same crate.这包括同一个 crate 中的二进制目标。 They might be coupled together in the project, but they are NOT part of library crate.它们可能在项目中耦合在一起,但它们不是 library crate 的一部分。

Binary targets in fact are all separate crates for all purposes of the build system that work the same as libraries that have lib.rs at their root and writing crate in them refers to root of that specific binary target.实际上,二进制目标都是用于构建系统的所有目的的独立 crate,它们的工作方式与以lib.rs为根的库相同,并且在其中编写crate是指该特定二进制目标的根。


Demo:演示:

#[derive(Debug)]
pub struct A;

mod b {
    #[derive(Debug)]
    pub struct B(pub crate::A);
}

fn main() {
    println!("{:?}", b::B(A));
}

Playground 操场

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

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