Why does this workaround to "can't use `Self` from outer item" work?

⚓ rust    📅 2025-05-22    👤 surdeus    👁️ 4      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

I would like to be able to call from within a method this compile-time assertion:

const _: () = assert!(Self::is_odd(123));

where is_odd is a const fn method.

This fails with can't use Self from outer item, which I can understand. Note that this is generated from within a macro so we do not have access to the qualified name of the struct and need to use Self.

My coworker found this workaround (inspired from the static_assert crate), which does work:

let _: [(); {
    if !Self::is_odd(123) {
        panic!("not odd!")
    };
    0
}] = [];

I don't really see why this is allowed and not the former. Is this a loophole that risks being closed one day, or can this be relied on?

Thanks for anyone able to enlighten me :slight_smile:

8 posts - 5 participants

Read full topic

🏷️ rust_feed