lotsoftools

Understanding Rust Error E0639

Rust Error E0639 Explained

Error E0639 occurs when you attempt to directly instantiate a struct, enum, or enum variant that is marked as non_exhaustive. The non_exhaustive attribute indicates that the data structure may have more fields or variants added in the future, and direct instantiation could lead to unintended side effects if those changes are made.

Code Example with Erroneous Usage

Here is an example of the erroneous code that produces Rust error E0639:

#[non_exhaustive]
pub struct NormalStruct {
    pub first_field: u16,
    pub second_field: u16,
}

let ns = NormalStruct { first_field: 640, second_field: 480 }; // error!

Using a new function or an equivalent approach provided by the crate's documentation can help solve this issue.

Replacing Direct Instantiation with a new Function

In the above example, to create an instance of NormalStruct, use a function provided by the crate's documentation. Here's an example of how to create a new function for instantiation:

pub struct NormalStruct {
    pub first_field: u16,
    pub second_field: u16,
}

impl NormalStruct {
    pub fn new(first_field: u16, second_field: u16) -> Self {
        NormalStruct { first_field, second_field }
    }
}

let ns = NormalStruct::new(640, 480);

In this example, the new method is defined within the impl block for NormalStruct. This method takes two parameters representing the fields and returns a new instance of NormalStruct. It solves the problem and ensures that future changes to the data structure won't cause unintended side effects.

Conclusion

To avoid error E0639 in Rust, always use a constructor function or a method provided by the crate documentation when instantiating non_exhaustive structs or enums. This allows for safe and manageable code evolution without side effects due to future changes in the data structures.