lotsoftools

Understanding Rust Error E0691

Error E0691: Overview

Rust Error E0691 occurs when a struct, enum, or union with the repr(transparent) representation hint contains a zero-sized field requiring non-trivial alignment. This error arises because a transparent struct, enum, or union should have the same representation as the data it contains. However, when a zero-sized field has a conflicting alignment requirement, it leads to an incompatibility.

Example of Erroneous Code

#![allow(unused)]
#![feature(repr_align)]

fn main() {
    #[repr(align(32))]
    struct ForceAlign32;

    #[repr(transparent)]
    struct Wrapper(f32, ForceAlign32); // error: zero-sized field in transparent
                                       //        struct has alignment larger than 1
}

Solutions for Error E0691

There are two ways to resolve Error E0691: 1. Remove the over-aligned zero-sized field from the transparent struct. 2. Use PhantomData<T> if you need to keep the zero-sized field for some reason.

Removing the Over-Aligned Zero-Sized Field

#![allow(unused)]
fn main() {
    #[repr(transparent)]
    struct Wrapper(f32);
}

Using PhantomData<T>

#![allow(unused)]
#![feature(repr_align)]

fn main() {
    use std::marker::PhantomData;

    #[repr(align(32))]
    struct ForceAlign32;

    #[repr(transparent)]
    struct Wrapper(f32, PhantomData<ForceAlign32>);
}

Additional Notes

It is important to note that empty arrays [T; 0] have the same alignment requirement as the element type T. Additionally, this error is reported conservatively even when the alignment of the zero-sized type is less than or equal to the data field's alignment.