您如何在 rust 中为“其他一切”设置默认的 #[cfg] 目标?

Dou*_*oug 5 rust

#[cfg] 助手非常晦涩,没有特别详细的记录,但是通过挖掘 librustc,我得到了所有可用配置目标的合理列表(target_os、target_family、target_arch、target_endian、target_word_size、windows、unix) ,当然你可以使用 not(..) 来指定组合。

但是,我无法弄清楚如何拥有“默认”实现。

有没有办法使用 cfg 做到这一点?

#[cfg(???)] <--- What goes here?
fn thing {
  panic!("Not implemented! Please file a bug at http://... to request support for your platform")
}

#[cfg(target_os = "mac_os"]
fn thing() {
  // mac impl 
}

#[cfg(target_os = "windows"]] 
fn thing() {
  // windows impl
}
Run Code Online (Sandbox Code Playgroud)

我看到 stdlib 有一些:

#[cfg(not(any(target_os = "macos", target_os = "ios", windows)]
Run Code Online (Sandbox Code Playgroud)

其中涉及大量繁琐的复制和粘贴。这是唯一的方法吗?

(恐慌很糟糕,对吧?不要那样做?这是一个 build.rs 脚本,你应该并且必须恐慌将错误提升到货物)

Nem*_*ric 6

其中涉及大量繁琐的复制和粘贴。这是唯一的方法吗?

从条件编译的文档和RFC来看,是的,这是唯一的方法。如果有一种方法可以指定:

#[cfg(other)]
fn thing {
Run Code Online (Sandbox Code Playgroud)

这会增加属性解析的复杂性cfg,因为编译器需要知道只有在或未定义thing时才会编译。mac_oswindows

另外,这个怎么样:

#[cfg(other)]
fn thing_some_other {
  panic!("Not implemented! Please file a bug at http://... to request support for your platform")
}

#[cfg(target_os = "mac_os"]
fn thing() {
  // mac impl 
}

#[cfg(target_os = "windows"]] 
fn thing() {
  // windows impl
}
Run Code Online (Sandbox Code Playgroud)

换句话说,它们需要连接在一起,类似于 C:

#ifdef WINDOWS
    // ...
#elif LINUX
     // ...
#else
     // ...
#endif
Run Code Online (Sandbox Code Playgroud)