liveBook · Manning

Public visibility

As explained in Idiomatic Rust

Visibility is the language-defined accessibility of a program item from a given scope or module.

Rust items are private by default. Adding `pub` exposes an item; on a struct field, it permits direct access and modification. Public fields generally suit data-only containers. Otherwise, keep fields private and expose access through methods. section 4.4

When shaping a public API:

  • Expose the struct and methods needed by external callers. Types returned by public methods must also be public. section 6.11.1
  • Keep fields private when access should be controlled, and provide public accessors, mutators, or setters as needed. section 4.4
Listing 4.8 A pizza with pub toppings
#[derive(Debug, Clone)]
pub struct Pizza {
    pub toppings: Vec<String>,            #1
}

A public `toppings` field allows callers to modify a pizza's data directly. section 4.4

Listing 4.9 Providing access to our pizza toppings
impl Pizza {
    pub fn toppings(&self) -> &[String] {          #1
        self.toppings.as_ref()
    }

    pub fn toppings_mut(&mut self) -> &mut Vec<String> {     #2
        &mut self.toppings
    }

    pub fn set_toppings(&mut self, toppings: Vec<String>) {  #3
        self.toppings = toppings;
    }
}

Public methods provide an alternative interface for reading and changing private toppings. section 4.4

How Idiomatic Rust covers it

How deep it goes
Defines `pub` for fields and items, contrasts direct access with methods, and traces compiler errors for private library interfaces.
Examples
Uses pizza toppings, a bicycle builder API, and a linked-list library tested from outside its crate.
What you can do after
Configure a library API by exposing required types and methods while keeping fields private where access needs control.
How it connects
Connects visibility to structs, methods, accessors, traits, builders, and integration tests.

Also explained in

Compare how 8 books explain public visibility →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.