9.1 Defining Structs

9.1.1 Basic Struct Definition

In Rust, a struct is defined using the struct keyword, followed by the struct's name and its fields enclosed in curly braces {}. Each field in the struct consists of a field name, a colon :, and the field's type. Fields are separated by commas.

struct StructName {
    field1: Type1,
    field2: Type2,
    // ...
}

Example:

#![allow(unused)]
fn main() {
struct Person {
    name: String,
    age: u8,
}
}
  • Fields: Each field has a name and a type, separated by a colon :.
  • Field List: Enclosed in curly braces {}, with fields separated by commas.
  • Naming Conventions: Struct names typically use CamelCase, while field names are written in snake_case.
  • Declaration: Struct types are usually declared at the module scope, though they can also be declared within functions.

Structs group related data together, enabling you to model more complex data types in your programs.

Comparison with C

C Code:

struct Person {
    char* name;
    uint8_t age;
};
  • In C, structs can be anonymous or named. In Rust, structs are always named.