Understanding Rust Error E0320: Recursion Limit Reached While Creating Drop-Check Rules
Overview of Rust Error E0320
Rust Error E0320 occurs when the Rust compiler encounters a type that has recursive drop-check rules, which prevents the compiler from generating the necessary code to properly drop a value. The error message reads: 'Recursion limit reached while creating drop-check rules.'
Example of Erroneous Code
#![allow(unused)]
fn main() {
enum A<T> {
B,
C(T, Box<A<(T, T)>>)
}
fn foo<T>() {
A::<T>::B; // error: overflow while adding drop-check rules for A<T>
}
}
Reasoning Behind the Error
In the example code above, the type 'A' has recursive drop-check rules, as it contains a variant 'C' which holds a tuple containing the type parameter 'T' and a boxed version of the type 'A'. Because of this recursion, the Rust compiler is unable to determine how to properly drop the type 'A', resulting in Error E0320.
The error differs from Rust Error E0072, which occurs when a type has an infinite size. Although the type in Error E0320 has a finite size, the recursion would cause an infinite loop when attempting to drop the value.
How to Resolve Rust Error E0320
To resolve this error, you must remove the recursion in the type's drop-check rules. One possible solution is to use the 'Option' enum, which can represent either 'Some' value or 'None' (null). The 'Option' enum can help break the recursive cycle, allowing the Rust compiler to generate proper drop-check rules.
Example of Fixed Code
#![allow(unused)]
fn main() {
enum A<T> {
B,
C(T, Option<Box<A<(T, T)>>>),
}
fn foo<T>() {
A::<T>::B; // no error encountered
}
}
In the fixed code example, we have replaced the 'Box<A<(T, T)>>' with 'Option<Box<A<(T, T)>>>'. This modification prevents the infinite recursion, allowing the Rust compiler to create the correct drop-check rules without encountering Error E0320.