相关疑难解决方法(0)

是否有可能有条件地启用像"derive"这样的属性?

我在我的箱子中添加了一个功能,增加了serde支持.但是,我不太明白如何正确使用它:

// #[derive(Debug, Serialize, Deserialize, Clone)] // goes to:

#[derive(Debug, Clone)]
#[cfg(feature = "serde_support")]
#[derive(Serialize, Deserialize)]
pub struct MyStruct;
Run Code Online (Sandbox Code Playgroud)

这段代码将下面的所有内容cfg(feature)视为有条件编译,因此如果没有我的serde_support功能,我的箱子也没有MyStruct.

我试图用大括号包装它,但它给出了另一个错误:

码:

#[derive(Debug, Clone)]
#[cfg(feature = "serde_support")] {
#[derive(Serialize, Deserialize)]
}
pub struct MyStruct;
Run Code Online (Sandbox Code Playgroud)

错误:

error: expected item after attributes
  --> mycrate/src/lib.rs:65:33
   |
65 | #[cfg(feature = "serde_support")] {
   |                                 ^
Run Code Online (Sandbox Code Playgroud)

那怎么做?

rust

19
推荐指数
1
解决办法
1775
查看次数

如何通过条件编译更改函数的限定符?

我有一个能够实现为const:

#![feature(const_fn)]

// My crate would have:

const fn very_complicated_logic(a: u8, b: u8) -> u8 {
    a * b
}

// The caller would have:

const ANSWER: u8 = very_complicated_logic(1, 2);

fn main() {}
Run Code Online (Sandbox Code Playgroud)

我想继续支持稳定的Rust,因为无法定义这样的函数.这些稳定的消费者将无法使用该功能在一个conststatic,但应该可以使用该功能在其他情况下:

// My crate would have:

fn very_complicated_logic(a: u8, b: u8) -> u8 {
    a * b
}

// The caller would have:    

fn main() {
    let answer: u8 = very_complicated_logic(1, 2);
}
Run Code Online (Sandbox Code Playgroud)

我如何有条件地编译我的代码,以便我的箱子的冒险用户可以启用const fn支持,稳定的用户仍然可以使用我的代码,而且我不必编写每个函数两次?

同样的问题应该适用于函数的其他修饰符,但我不确定这些修饰符会根据某些条件发生变化的具体情况:

  • default
  • unsafe …

conditional-compilation rust

9
推荐指数
1
解决办法
168
查看次数

标签 统计

rust ×2

conditional-compilation ×1