导入模块时使用未声明的不稳定模块并使用cfg属性

时间:2017-05-29 19:37:01

标签: import module rust

我有以下代码:

#[cfg(all(feature = "unstable", unique))]
#[cfg(all(feature = "unstable", heap_api))]
#[cfg(all(feature = "unstable", alloc))]

use std::ptr::Unique;
use std::mem;
use alloc::heap;

pub struct Foo<T> {
    arr: Unique<T>,
    cap: usize,
    probe_limit: usize,
}

但是,当我尝试使用cargo build --features "unstable"编译它时,我收到编译错误。请注意,我正在使用Rust的每晚构建,并且不正确的功能设置正确(否则我会得到不同的错误)。

error[E0412]: cannot find type `Unique` in this scope
  --> src/hash/arr.rs:27:8
   |
27 |   arr: Unique<T>,
   |        ^^^^^^ not found in this scope
   |
help: possible candidate is found in another module, you can import it into scope
   | use std::ptr::Unique;

我不确定为什么找不到Unique。我应该在我的文件顶部使用它。 use ::std::ptr::Unique不起作用。

1 个答案:

答案 0 :(得分:3)

让我们解构你的cfg指令:

#[cfg(all(feature = "unstable", unique))]

这是一个outer属性,这意味着它将在要更改的项目之外,并将应用于下一个项目。使用cfg属性,表示&#34;如果括号内的功能已启用,请执行下一个块&#34;,all是功能之间的AND。所以你有类似&#34;如果启用了功能不稳定和唯一,请执行下一个语句。

Attributes!如果您在命令行中设置了功能inner,那么您需要有条件地拥有feature(unique)属性unstable。可以使用cfg_attr获取条件属性。

#![cfg_attr(feature = "unstable", feature(unique))]

可以将其视为启用了功能unstable,然后启用内部feature(unique)。然后,您就可以使用std::ptr::Unique

您还应该在#[cfg(feature = "unstable")]use之前添加struct,这样如果未启用该功能,它们将无法使用。