Writing a library with a Windows and a Unix implementation?


I’m playing around with implementing Termbox in Rust since the existing libraries only wrap the C library and so don’t provide support for the Windows Console. As I’m doing this, I’m thinking about what it would take to make the library support both Windows and Unix.

What are the “accepted” ways to write a library that supports both Windows and Unix through largely different OS APIs? Are there good, and relatively simple, examples of libraries that do this? It would be nice to be able to share some of the code, but I’m not really sure where or how to do all that.


The usual pattern is to do something like this (i didn’t compile this, but it should be close):

mod sys {
    mod nix {

    mod win {

use sys::win as sys;
use sys::nix as sys;

This isolates the specific bits. You then give both modules the same external interface, and write the code in common on top. Does that make sense?


“write the code in common on top” - like?

pub mod api {
    pub fn some_function() {


Yes. You can see this pattern in the standard library. Well, actually:

It’s sliiightly different but ends up as the same thing:

These then get used like this:


both get used like this:

So that Thread::new is correct on both systems.