Understanding Rust Error E0742: Invalid Restricted Visibility
Introduction to Rust Error E0742
Rust error E0742 occurs when an item has a restricted visibility specifier that refers to a module which isn't an ancestor of the item itself. It means that the visibility of a struct, enum or function is set to a module that cannot access the item based on the module hierarchy.
Understanding the Error E0742 Code Example
Let's consider the erroneous code example provided in the official Rust documentation:
pub mod sea {}
pub (in crate::sea) struct Shark; // error!
fn main() {}
In this example, the error occurs because the visibility of the Shark struct is specified as pub (in crate::sea), which means that the struct should be accessible only within the sea module. However, the Shark struct is defined outside the sea module.
Fixing Rust Error E0742
To fix Rust error E0742, we need to move the item with restricted visibility inside the ancestor module it refers to. In our example, we can move the Shark struct inside the sea module:
pub mod sea {
pub (in crate::sea) struct Shark; // ok!
}
fn main() {}
The issue is resolved because the Shark struct is now within the sea module and its visibility is restricted to the same module.
Using Ancestor Module for Restricted Visibility
You can also use an ancestor module for restricted visibility. For example, if we have a nested module structure:
pub mod earth {
pub mod sea {
pub (in crate::earth) struct Shark; // ok!
}
}
fn main() {}
Here, the Shark struct is defined within the sea module, a nested module inside the earth module. The restricted visibility of the Shark struct is set to the earth module, which is an ancestor of the sea module. Therefore, no error occurs.