Detecting Rust Edition Puzzle

I needed to write some code code to detect rust edition. I ended needing a different solution to my problem, but I think it could make an interesting coding puzzle.

I have 2021 and 2024 detection at both runtime and compile time. How would you do if for other editions? No using build.rs or external crates.

// https://doc.rust-lang.org/edition-guide/rust-2024/macro-fragment-specifiers.html
// invoke like: edition_guard !(const {});
macro_rules! edition_guard {
    ($e:expr) => {
        compile_error!("Edition 2024 is currently unsupported. Use the 2021 Edition.")
    };
    (const $e:expr) => {
        println!("second rule");
    };
}
edition_guard!(const {});

// https://doc.rust-lang.org/edition-guide/rust-2024/temporary-tail-expr-scope.html
fn which_edition() -> i32 {
    use ::std::{cell::RefCell, rc::Rc};
    struct WhichEdition(Rc<RefCell<i32>>);
    impl Drop for WhichEdition {
        fn drop(&mut self) {
            *self.0.borrow_mut() += 3;
        }
    }

    let rc = Rc::new(RefCell::new(2021));
    if let None = Some(WhichEdition(rc.clone())) {
        unreachable!()
    }
    // <------- dropped here in 2024
    else {
        *rc.borrow()
    }
    // <------- dropped here in 2021
}

fn main() {
    let edition = which_edition();

    fn main() {}

    println!("{edition}");
}

Here's a way to distinguish between 2015 and 2018+ via use path behavior.

3 Likes