liveBook · Manning

Attribute

As explained in Code Like a Pro in Rust

A struct field is an element of a struct value with a declared type and, in regular structs, a name.

Rust attributes can generate trait implementations, request C-compatible struct representation, and enable compiler warnings. section 4.4.2 section 4.8 section 2.8

Use attributes for distinct implementation needs:

  • `#[derive(...)]` generates trait implementations. For `HashMap` keys, derive `Hash` and `Eq`; `Eq` also requires `PartialEq`. `Debug` can help with debugging and tests. section 4.4.2
  • `#[repr(C)]` requests a C-compatible struct representation for FFI. Use C types from `libc`; `rust-bindgen` can generate bindings from C headers. section 4.8
  • `#![warn(missing_docs)]` enables a compiler warning for missing documentation; `cargo doc` generates the project documentation. section 2.8
Listing 4.10 Code listing for a compound key type
#[derive(Hash, Eq, PartialEq, Debug)]
struct CompoundKey {
   name: String,
   value: i32,
}

See a compound struct deriving `Hash`, `Eq`, `PartialEq`, and `Debug`. section 4.4.2

#[repr(C)]             #1
struct GzFileState {   #2
    have: c_uint,
    next: *mut c_uchar,
    pos: i64,
}

See a C-compatible Rust struct using `#[repr(C)]` and C-mapped field types. section 4.8

How Code Like a Pro in Rust covers it

How deep it goes
Shows attribute effects with code examples, while deferring detailed treatment of derive and traits.
Examples
Uses a compound HashMap key, a C-mapped struct, and a missing-documentation warning.
What it assumes
Assumes familiarity with Rust structs and traits; treats derive as automatic implementation generation rather than teaching trait internals.
What you can do after
Apply derive, repr(C), and lint attributes to implement traits, support FFI structs, and check documentation.
How it connects
Connects derive attributes with traits and HashMap keys, repr(C) with FFI, and lint attributes with rustdoc.

Also explained in

Compare how 26 books explain attribute →

Related concepts

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