Hacker News new | ask | show | jobs
by geogriffin 1936 days ago
FWIW, you can write the conditional compilation example like so:

  fn read_keys(#[cfg(feature = "splitapple")]
               port: nrf52840_hal::pac::P1,
               #[cfg(feature = "keytron")]
               port: nrf52833_hal::pac::P0) -> Packet {}
I suppose the compiler could try to suggest that as a fix.
2 comments

Another option would be to define a type alias:

    #[cfg(feature = "splitapple")]
    type Port = nrf52840_hal::pac::P1;

    #[cfg(feature = "keytron")]
    type Port = nrf52833_hal::pac::P0;

    fn read_keys(port: Port) -> Packet {}

but I think the whole problem here is that author tried to do what would have been #ifdef in C, but that doesn't get you far in Rust when macros are AST-based and types are more specific than `int` and `char*`.

A more "rustic" solution would be to use a trait, e.g.

    trait ReadKeys {
       type Port;
       fn read_keys(Self::Port) -> Packet {}
    }

    impl ReadKeys for Splitapple {…}
    impl ReadKeys for Keytron {…}
My experience with Rust has been that it's possible to do almost anything, but that doesn't mean it's necessarily obvious or ergonomic to do so, or that anyone else will understand my code when its finished.