Struct / Record
Overview
A Record (also called a Struct) is a non-primitive data type that groups multiple related fields, possibly of different data types, into a single unit. Each field has a name, making the structure self-describing and easy to work with.
Records model real-world entities cleanly and explicitly.
What Is a Record / Struct?
A record:
- Combines heterogeneous data
- Uses named fields
- Represents a single logical entity
Each field is accessed by its name, not by position.
How It Works
When a record is defined:
- Memory is allocated for all fields
- Fields are laid out sequentially (with possible padding)
- Each field has a fixed offset
Access uses:
record.fieldName
Example
Pseudocode
struct Person {
name: String
age: Integer
isEmployed: Boolean
}
p = Person("Anita", 30, true)
print(p.age)
CommonOperations
| Operation | Description |
|---|---|
| Creation | Allocate and initialize fields |
| Field access | Read or write a field |
| Assignment | Copy or reference-based |
| Comparison | Field-wise (language dependent) |
Real-world Analogy
A record is like a form with labeled fields. Each label tells you exactly what the value represents 📝.
Time and Space Complexity
- Space: O(n), where n is number of fields
- Field access: O(1)
Use Cases
- Modeling entities (users, products, sensors)
- Data transfer objects
- Configuration records
- Database row representations
Advantages
- Improves code readability
- Groups related data
- Type-safe field access
Limitations
- Fixed structure once defined
- No built-in behavior (without methods)
- Large records may increase copy cost
Record vs Array
| Aspect | Record | Array |
|---|---|---|
| Field types | Different | Same |
| Access | By name | By index |
| Semantics | Descriptive | Positional |