Understanding Rust Error E0704: Incorrect Visibility Restriction

Introduction to Rust Error E0704

Rust Error E0704 occurs when an incorrect visibility restriction is specified for a module, struct or function. This error signifies that the programmer has made a mistake in applying visibility restrictions, which results in code that cannot compile. In this article, we will expound on the official Rust documentation in order to provide a deeper understanding of E0704.

Example of Erroneous Code

fn main() {
mod foo {
    pub(foo) struct Bar {
        x: i32

In the code snippet above, the programmer attempts to use a visibility restriction pub(foo) on the struct Bar. This is an incorrect usage of visibility restrictions, resulting in Rust Error E0704.

Correcting Code using the in Keyword

To fix Rust Error E0704, one must use the in keyword to specify the proper visibility restriction. The corrected code should look like this:

mod foo {
    pub(in crate::foo) struct Bar {
        x: i32

fn main() {}

In the updated code, the visibility of struct Bar is properly restricted to module foo with the pub(in crate::foo) syntax.

More Examples: Different Types of Visibility

When working with Rust, it is important to understand different types of visibility restrictions. Here are some examples:

1. Public visibility:

pub mod library {
    // Can be accessed from anywhere

In this example, the mod library is declared as public using the pub keyword, and it can be accessed from anywhere.

2. Private (default) visibility:

mod private_library {
    // Can be accessed only from the current module

In this example, the mod private_library does not have a specific visibility keyword. It defaults to private and is accessible only from the current module.

3. Restricted visibility:

pub(in crate::library) mod restricted_library {
    // Can be accessed only within crate::library

In this example, the mod restricted_library is given restricted visibility using pub(in crate::library). It is accessible only within the specified module, crate::library.