Re: [PATCH 5/7] rust: init: add `..Zeroable::zeroed()` syntax for zeroing all missing fields
From: Benno Lossin
Date: Sun Jun 25 2023 - 09:07:27 EST
On 25.06.23 14:56, Björn Roy Baron wrote:
> On Saturday, June 24th, 2023 at 23:14, Benno Lossin <benno.lossin@xxxxxxxxx> wrote:
>>>> + // Ensure that the struct is indeed `Zeroable`.
>>>> + is_zeroable(slot);
>>>> + // SAFETY: The type implements `Zeroable` by the check above.
>>>> + unsafe { ::core::ptr::write_bytes(slot, 0, 1) };
>>>> + $init_zeroed // this will be `()` if set.
>>>
>>> How does this work? Shouldn't there be a ; after $init_zeroed to consume the () value?
>>
>> It is the last expression of a block and since it is `()` it is ok
>> (adding a ; would also be ok, but it is not necessary).
>
> I'm surprised it is considered the last expression of a block. Unlike with {} using $()? will still
> allow variables defined inside this as if they were outside of it. Also I can't reproduce this
> behavior with:
>
> macro_rules! foo {
> ($($a:expr)?) => {
> $($a)?
> bar();
> }
> }
>
> fn main() {
> foo!(());
> }
>
> Is there something I'm missing?
>
> Cheers,
> Björn
Not sure what you mean with "allow variables defined inside this
as if they were outside of it". But note that in the macro `$init_zeroed`
is the last expression of a block. Here is a small example:
```
macro_rules! foo {
($($a:expr)?) => {{
$(
bar();
$a
)?
}};
}
fn bar() {}
fn main() {
foo!(());
foo!();
}
```
it expands to this:
```
fn main() {
{
bar();
()
};
{};
}
```
--
Cheers,
Benno