Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you have a default #[cfg] target in rust for 'everything else'?

Tags:

rust

The #[cfg] helper is pretty obscure, and not particularly well documented, but by digging through librustc I've got a pretty reasonable list of all the available config targets(target_os, target_family, target_arch, target_endian, target_word_size, windows, unix), and of course you can use not(..) to specify combinations.

However, I can't figure out how to have a 'default' implementation.

Is there some way of doing this using 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
}

I see the stdlib has some:

#[cfg(not(any(target_os = "macos", target_os = "ios", windows)]

Which involves a lot of tedious copy and paste. Is that the only way?

(Panics are bad right? Don't do that? This is for a build.rs script, where you should and must panic to raise the error up to cargo)

like image 409
Doug Avatar asked Dec 11 '14 08:12

Doug


1 Answers

Which involves a lot of tedious copy and paste. Is that the only way?

Judging by the documentation and RFCs on conditional compilation, yes, this is the only way. If there would be a way to specify:

#[cfg(other)]
fn thing {

that would increase the complexity in the parsing of cfg attribute because compiler would need to know that thing would be compiled only if mac_os or windows are not defined.

Also, what about this:

#[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
}

In other words, they would need to be tied together, akin to C's:

#ifdef WINDOWS
    // ...
#elif LINUX
     // ...
#else
     // ...
#endif
like image 71
Nemanja Boric Avatar answered Sep 19 '22 12:09

Nemanja Boric