liveBook · Manning

Attribute

As explained in Learn Rust in a Month of Lunches

A struct field is a named or positional component of a Rust struct whose visibility can be declared independently of the struct type.

A struct field is one piece of data stored in a Rust struct. A named struct gives each field a name and a type; a tuple struct lists types without field names. You access a named field with a dot and its name, or a tuple field by position, such as `.1`. section 4.1.1

Give every field a value

`Country` has `population`, `capital`, and `leader_name` fields. Creating a `Country` requires a value for each one. If a variable has the same name as its field, `population` can stand in for `population: population`. section 4.1.1

Making a struct `pub` does not make its fields public. Add `pub` to each field that users should access. The same rule applies to tuple structs: `pub Email(String)` exposes the type but not its `.0` field; `pub Email(pub String)` exposes both. Keeping a field private lets a public constructor choose its value instead. section 14.1.2

mod print_things {
 
    #[derive(Debug)]
    pub struct Billy {                               #1
        name: String,
        pub times_to_print: u32,
    }
 
    impl Billy {
        pub fn new(times_to_print: u32) -> Self {    #2
            Self {
                name: "Billy".to_string(),           #3
                times_to_print,
            }
        }
        pub fn print_billy(&self) {
            for _ in 0..self.times_to_print {
                println!("{}", self.name);
            }
        }
    }
}
 
fn main() {
    use print_things::*;
 
    let my_billy = Billy::new(3);                    #4
    my_billy.print_billy();
}

This example keeps `name` private, makes `times_to_print` public, and uses `new` to set the private field. section 14.1.2

One easy terminology mix-up: Rust also calls `#[derive(Debug)]` an attribute. That is a compiler-interpreted annotation, not a struct field. section 13.1.5

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains field declarations, initialization, access, and separate visibility, without descending into representation internals.
Examples
Shows a three-field `Country`, positional `ColorRgb` access, and a public struct with one private and one public field.
What it assumes
Teaches struct forms and field syntax directly, then uses modules to show why field visibility matters.
What you can do after
Operate/configure it by initializing struct fields and choosing which fields callers can access with `pub`.
How it connects
Connects fields to named structs, tuple structs, modules, constructors, and `pub` visibility.

Also explained in

Compare how 26 books explain attribute →

Related concepts

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