Skip to main content

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:

  1. Memory is allocated for all fields
  2. Fields are laid out sequentially (with possible padding)
  3. 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

OperationDescription
CreationAllocate and initialize fields
Field accessRead or write a field
AssignmentCopy or reference-based
ComparisonField-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

AspectRecordArray
Field typesDifferentSame
AccessBy nameBy index
SemanticsDescriptivePositional