How to enforce your code is providing a specific API?


#1

Often times, you’ll write various versions of the same API. Is there a convenient way to check or enforce that your code is adhering to some API? Meaning the types of various named items are what you expect? In C you have header files that you can use for this purpose. Some example usages:

  • Checking that the stable API you promised to your users hasn’t changed
  • Keeping various versions of a mod imp depending on some #[cfg()] consistent (this is also a common pattern in std)

NB using traits is not sufficient, because not every item can be expressed as a trait member.


#2

You can have a non-cfg’d wrapper over the cfg’d APIs. This also allows you to only have to add documentation in one place: https://github.com/sfackler/rust-native-tls/blob/master/src/lib.rs


#3

That is probably a good enough solution for no. 2 in practice (although type inference/casting could have unintended consequences), but it definitely doesn’t address no. 1.


#4

It seems basically equivalent to C headers, unless I’m missing something.