Insulating layer?
Insulating layer?
Posted Oct 11, 2024 14:29 UTC (Fri) by adobriyan (subscriber, #30858)In reply to: Insulating layer? by asahilina
Parent article: On Rust in enterprise kernels
struct S {
int a;
#ifdef CONFIG_B
int b;
#endif
};
I've seen std::conditional_t implementation on some video (which looks almost exactly like C++ version) which makes me think they can not.
Posted Oct 11, 2024 15:11 UTC (Fri)
by farnz (subscriber, #17727)
[Link]
That's built-in, and can be done via macros, or via the existing #[cfg] attribute. Macros in general in Rust get an AST, and output a new AST, so can do pretty much anything (noting that only function-like macros get an arbitrary AST; attribute macros and derive macros must be given valid Rust source code).
But using the built-in #[cfg] mechanism, along with feature flags, you'd write that as:
This says that the field b only exists if the feature flag "config_b" is set at compile time; there's also preset cfg items, like target_has_atomic, which lets you write #[cfg(target_has_atomic = "64")] to only include a chunk of code on platforms with support for 64 bit atomics.
Posted Oct 11, 2024 15:26 UTC (Fri)
by khim (subscriber, #9252)
[Link]
You don't need macros for that because that's handled by separate facility in Rust. You probably misunderstood the precise limitation, I'm afraid. Macros in Rust are incredibly powerful, but they still work with a token trees. You can support configurable code and conditional compilation with them just fine, but they don't have access to the type information. If you go from C++ to Rust then yes, this limitation feels quite stifling. If you go from C to Rust… nope: C simply doesn't have anything similar to reflection. magic_enum couldn't be replicated in Rust, but then it doesn't work with C, either.
Insulating layer?
struct S {
a: i32,
#[cfg(feature = "config_b")]
b: i32
}
Insulating layer?
std::conditional_t
(and whatever Rust equivalent you saw) work with types, not with define
s, and yes, that's something macros couldn't touch (neither in C/C++ nor in Rust) simply because macros work before types come into existence.