A Rust struct groups fields of other types into one compound type. Use it to hold state, provide methods that operate on that state, or keep internal state behind an API. A functions-only API is also possible; a struct is not required merely to specify an interface. section 4.5 section 4.5.3
Choose a form that fits the data and its callers:
- A regular struct names and types its fields. Fields have module visibility by default; set visibility per field when callers need access. Prefer keeping fields private when methods can provide the needed operations. section 4.5.3
- A tuple struct has typed fields without names, accessed by position. It saves field names but can make their meaning ambiguous. Unit structs have no fields. section 4.5.3
- Use an impl block for methods. A method taking &mut self changes the existing value; one taking mut self and returning Self consumes the value and returns its updated form. section 4.5.3
- Derive common trait implementations such as Debug, Clone, and Default when the generated behavior is sufficient. section 4.5.3 section 4.9
pub struct MixedVisibilityStruct { #1
pub name: String, #2
pub(crate) value: String, #3
pub(super) number: i32, #4
}
Field visibility can differ within one public struct: pub, pub(crate), and pub(super) grant different scopes of access. section 4.5.3
impl DebuggableStruct {
fn increment_number(&mut self) { #1
self.number += 1;
}
}
The &mut self receiver lets increment_number modify a field on an existing value. section 4.5.3
A Rust struct is not automatically compatible with a C struct. At a foreign-function boundary, use #[repr(C)] for a C-compatible representation and map fields to appropriate C types rather than assuming similarly named Rust types match. Prefer rust-bindgen for C-header bindings; for a small manual binding, copy the C definition, convert its types, and declare the function interfaces. section 4.8
#[repr(C)] #1
struct GzFileState { #2
have: c_uint,
next: *mut c_uchar,
pos: i64,
}
The zlib state mapping pairs #[repr(C)] with C-oriented field types, including c_uint and a mutable c_uchar pointer. section 4.8













