Programming Search⌘K

Conceptintro

Record type

Also called record, record type, struct, structure, data class, named fields, compound data type, user-defined type.

A record groups a fixed set of named fields, each with its own type. Programs read a field by name and often make an updated copy in place of a change.

Applies to
core-languages

Idea

A record is a group of values with names. A date has a year, a month and a day. A person has a name and an age. Wikipedia defines a record as "a collection of fields, possibly of different data types, typically fixed in number and sequence".1 Each field has a name and a type, and the type of the record lists them.

from dataclasses import dataclass, replace


@dataclass(frozen=True)
class Person:
    name: str
    age: int


ada = Person(name="Ada", age=36)
print(ada.name, ada.age)

older = replace(ada, age=ada.age + 1)
print(older)
print(ada)
Output
Ada 36
Person(name='Ada', age=37)
Person(name='Ada', age=36)

A record is a product type whose parts have names (see Product type). The names make the code clear. Rust says it: "Unlike with tuples, in a struct you'll name each piece of data so it's clear what the values mean."2 The names also free the code from the order of the fields: "You don't have to rely on the order of the data to specify or access the values of an instance."2

How it works

Define, build and read. A record type declares its fields. A value is built with one value for each field, usually by name, as in the call Person(name=n, age=a). A field is read with a dot, as in ada.name. Swift structures get "an automatically generated memberwise initializer", whose arguments are the fields by name.3

Update by copy. Many records are immutable. To change one field, the program makes a new record that has the new value in that field and the old values in the other fields. Most languages have a short form for this:

Language Copy with a change
OCaml { p with age = 37 } builds "a fresh record" with the other fields from p4
F# { p with Age = 37 }, a copy and update record expression5
Rust Person { age: 37, ..p }, the struct update syntax2
C# p with { Age = 37 }, which "creates a copy of its operand with the specified properties and fields modified"6
Kotlin p.copy(age = 37)7
Python dataclasses.replace(p, age=37)8
JavaScript, TypeScript { ...p, age: 37 }, with spread syntax9

The copy is shallow. OCaml says that the with expression "returns a shallow copy of the record expr, except for the fields field1 … fieldn".4 So a field that holds a mutable object is shared between the old and the new record. The Pitfalls show the result.

Generated methods. A record usually comes with methods that the compiler writes. The C# record modifier makes the compiler "generate value equality", a formatted ToString, and "nondestructive mutation through with expressions".10 A Kotlin data class gets equals(), hashCode(), toString(), componentN() functions and copy().7 A Python dataclass gets generated methods "such as init() and repr()".8 Java records are "classes that act as transparent carriers for immutable data".11

Values and references. In some languages a record is a value. Assignment copies all the fields. In Swift, a value type "is a type whose value is copied when it's assigned to a variable or constant, or when it's passed to a function".3 C structs, Go structs, Rust structs and C# record struct types behave this way. In other languages a record is an object, and assignment copies a reference. Java records, C# record class types, Kotlin data classes and Python dataclasses behave this way. With a reference, a change through one name is visible through all names, so records of this kind are often immutable.

Nominal and structural. In most languages, two record types with the same fields are still two different types, because the type has a name. Java calls records "nominal tuples".11 TypeScript compares object types by their fields, so any object with the right fields has the type. OCaml finds the record type from the field names that an expression uses.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptIdiom
TypeScriptNative
GoNative
RustNative
KotlinNativeA data class is a record with generated equals, hashCode, toString, componentN and copy functions; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLNativeA row of a table is a record with one field for each column.
BashIdiomBash has no record type, but an associative array can hold one key for each field.
PowerShellIdiomA pscustomobject or a class holds named properties; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no types.
CSSDoes not applyStyle rules have no types.
Regular expressionsDoes not applyA pattern has no types.

The example files define a Person record, read a field, make a copy with a new age, and compare two records.

Language Verdict Form
Python native a @dataclass, frozen for an immutable record8
JavaScript idiom an object literal; Object.freeze for an immutable record
TypeScript native an object type with readonly fields12
Java native a record11
C native a struct
C++ native a struct, an aggregate
C# native a record, a record struct or a struct10
Go native a struct
Rust native a struct2
Kotlin native a data class7
PowerShell idiom a [pscustomobject] or a class
Bash idiom an associative array with one key for each field
SQL native a row of a table, with one column for each field
Regex n/a a pattern has no types
HTML/CSS n/a markup has no types

Python. @dataclass(frozen=True) makes the fields read-only after construction. dataclasses.replace "Creates a new object of the same type as obj, replacing fields with values from changes".8

JavaScript and TypeScript. An object is a record of properties. In an object literal, the spread syntax "enumerates the properties of an object and adds the key-value pairs to the object being created".9 In TypeScript, the type checker refuses a write to a readonly property, but the mark does not change any behavior at run time.12

Java. For each component, a record class gets a private final field and a public accessor method with the same name. It also gets a canonical constructor and implicit equals, hashCode and toString methods. Java 16 made records a standard feature.11 Java has no short form for a copy with a change, so code calls the constructor with all the fields.

C, C++ and Go. A struct is a value. Assignment copies every field, so a copy with a change is an assignment followed by a write to one field. C has no == for structs, so a program compares the fields one by one. In Go, "Struct types are comparable if all their field types are comparable", and == compares them field by field.13

PythonGitHub
from dataclasses import FrozenInstanceError, dataclass, replace


@dataclass(frozen=True)
class Person:
    name: str
    age: int


def yn(b: bool) -> str:
    return "yes" if b else "no"


ada = Person(name="Ada", age=36)
print("name:", ada.name, "age:", ada.age)

older = replace(ada, age=ada.age + 1)
print("copy:", older)
print("original:", ada)
print("same fields equal:", yn(ada == Person("Ada", 36)))

try:
    ada.age = 40
except FrozenInstanceError:
    print("assignment refused: yes")
Output
name: Ada age: 36
copy: Person(name='Ada', age=37)
original: Person(name='Ada', age=36)
same fields equal: yes
assignment refused: yes
  • Verdict: native. A dataclass is a record with generated __init__, __repr__ and __eq__ methods.
  • replace makes a new object and leaves the original unchanged.
  • frozen=True makes an assignment to a field raise FrozenInstanceError.
#include <iostream>
#include <string>

struct Person {
    std::string name;
    int age;

    bool operator==(const Person&) const = default;
};

std::ostream& operator<<(std::ostream& os, const Person& p) {
    return os << "Person{" << p.name << ", " << p.age << "}";
}

int main() {
    Person ada{.name = "Ada", .age = 36};
    std::cout << "name: " << ada.name << " age: " << ada.age << "\n";

    Person older = ada;  // copies every member, including the string
    older.age += 1;
    std::cout << "copy: " << older << "\n";
    std::cout << "original: " << ada << "\n";

    Person other{.name = "Ada", .age = 36};
    std::cout << "same fields equal: " << (ada == other ? "yes" : "no") << "\n";
}
Output
name: Ada age: 36
copy: Person{Ada, 37}
original: Person{Ada, 36}
same fields equal: yes
  • Verdict: native. A struct with public members is an aggregate, a record that brace initialization fills.
  • A defaulted operator== (C++20) compares the members in order.
  • Copying a Person copies the std::string too, so the copy shares nothing with the original.
JavaGitHub
public class Main {
    record Person(String name, int age) {
        Person withAge(int newAge) {
            return new Person(name, newAge);
        }
    }

    static String yn(boolean b) {
        return b ? "yes" : "no";
    }

    public static void main(String[] args) {
        Person ada = new Person("Ada", 36);
        System.out.println("name: " + ada.name() + " age: " + ada.age());

        Person older = ada.withAge(ada.age() + 1);
        System.out.println("copy: " + older);
        System.out.println("original: " + ada);
        System.out.println("same fields equal: " + yn(ada.equals(new Person("Ada", 36))));
    }
}
Output
name: Ada age: 36
copy: Person[name=Ada, age=37]
original: Person[name=Ada, age=36]
same fields equal: yes
  • Verdict: native. A record gets a private final field and a public accessor for each component, and generated equals, hashCode and toString.
  • Java has no copy-with-change syntax, so the record declares a withAge method that calls the constructor.
  • The fields are final, so a record cannot change after construction.
#include <stdio.h>
#include <string.h>

struct person {
    const char *name;
    int age;
};

static void show(const char *label, struct person p) {
    printf("%s{name=%s, age=%d}\n", label, p.name, p.age);
}

static int person_equal(struct person a, struct person b) {
    return strcmp(a.name, b.name) == 0 && a.age == b.age;
}

int main(void) {
    struct person ada = {.name = "Ada", .age = 36};
    printf("name: %s age: %d\n", ada.name, ada.age);

    struct person older = ada; /* assignment copies every member */
    older.age += 1;
    show("copy: ", older);
    show("original: ", ada);

    struct person other = {.name = "Ada", .age = 36};
    printf("same fields equal: %s\n", person_equal(ada, other) ? "yes" : "no");
    return 0;
}
Output
name: Ada age: 36
copy: {name=Ada, age=37}
original: {name=Ada, age=36}
same fields equal: yes
  • Verdict: native. A struct is a record. Designated initializers such as .age = 36 set fields by name.
  • C has no == for structs, so person_equal compares the members. It compares the strings with strcmp, not the pointers.
  • The copy is shallow: older.name points to the same characters as ada.name.
var ada = new Person("Ada", 36);
Console.WriteLine($"name: {ada.Name} age: {ada.Age}");

var older = ada with { Age = ada.Age + 1 };
Console.WriteLine($"copy: {older}");
Console.WriteLine($"original: {ada}");
Console.WriteLine("same fields equal: " + Yn(ada == new Person("Ada", 36)));
Console.WriteLine("same object: " + Yn(ReferenceEquals(ada, new Person("Ada", 36))));

static string Yn(bool b) => b ? "yes" : "no";

record Person(string Name, int Age);
Output
name: Ada age: 36
copy: Person { Name = Ada, Age = 37 }
original: Person { Name = Ada, Age = 36 }
same fields equal: yes
same object: no
  • Verdict: native. A positional record gets init-only properties, value equality, a formatted ToString and support for with.
  • with makes a new object. The original keeps its age.
  • A record is a reference type, but == compares the members. record struct makes a value type.
JavaScriptGitHub
const yn = (b) => (b ? "yes" : "no");

const ada = Object.freeze({ name: "Ada", age: 36 });
console.log("name:", ada.name, "age:", ada.age);

const older = { ...ada, age: ada.age + 1 };
console.log("copy:", JSON.stringify(older));
console.log("original:", JSON.stringify(ada));

const other = { name: "Ada", age: 36 };
const samePerson = (a, b) => a.name === b.name && a.age === b.age;
console.log("same fields equal:", yn(samePerson(ada, other)));
console.log("same fields, ===:", yn(ada === other));
Output
name: Ada age: 36
copy: {"name":"Ada","age":37}
original: {"name":"Ada","age":36}
same fields equal: yes
same fields, ===: no
  • Verdict: idiom. A plain object is a record of properties. Object.freeze stops later changes to the properties.
  • The spread ...ada copies the properties into a new object, and the later age overrides the copied one.
  • === compares identity, so record equality needs a function that compares the fields.
TypeScriptGitHub
type Person = { readonly name: string; readonly age: number };

const yn = (b: boolean): string => (b ? "yes" : "no");

const ada: Person = { name: "Ada", age: 36 };
console.log(`name: ${ada.name} age: ${ada.age}`);

const older: Person = { ...ada, age: ada.age + 1 };
console.log("copy: " + JSON.stringify(older));
console.log("original: " + JSON.stringify(ada));

const other: Person = { name: "Ada", age: 36 };
const samePerson = (a: Person, b: Person): boolean => a.name === b.name && a.age === b.age;
console.log("same fields equal: " + yn(samePerson(ada, other)));
console.log("same fields, ===: " + yn(ada === other));
Output
name: Ada age: 36
copy: {"name":"Ada","age":37}
original: {"name":"Ada","age":36}
same fields equal: yes
same fields, ===: no
  • Verdict: native. An object type with readonly fields describes an immutable record. The type checker refuses ada.age = 40.
  • readonly exists only at type-checking time. The program at run time is plain JavaScript.
  • Object types are structural: any object with a name string and an age number is a Person.
package main

import "fmt"

type Person struct {
	Name string
	Age  int
}

func yn(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	ada := Person{Name: "Ada", Age: 36}
	fmt.Println("name:", ada.Name, "age:", ada.Age)

	older := ada // assignment copies every field
	older.Age++
	fmt.Printf("copy: %+v\n", older)
	fmt.Printf("original: %+v\n", ada)
	fmt.Println("same fields equal:", yn(ada == Person{"Ada", 36}))
}
Output
name: Ada age: 36
copy: {Name:Ada Age:37}
original: {Name:Ada Age:36}
same fields equal: yes
  • Verdict: native. A struct is a record. A struct value is copied on assignment and when it is passed to a function.
  • == compares the fields when all field types are comparable.
  • Go has no read-only fields. To keep a record unchanged, pass it by value or keep its fields unexported.
RustGitHub
#[derive(Debug, Clone, PartialEq)]
struct Person {
    name: String,
    age: u32,
}

fn yn(b: bool) -> &'static str {
    if b { "yes" } else { "no" }
}

fn main() {
    let ada = Person {
        name: String::from("Ada"),
        age: 36,
    };
    println!("name: {} age: {}", ada.name, ada.age);

    let older = Person {
        age: ada.age + 1,
        ..ada.clone()
    };
    println!("copy: {:?}", older);
    println!("original: {:?}", ada);

    let other = Person {
        name: String::from("Ada"),
        age: 36,
    };
    println!("same fields equal: {}", yn(ada == other));
}
Output
name: Ada age: 36
copy: Person { name: "Ada", age: 37 }
original: Person { name: "Ada", age: 36 }
same fields equal: yes
  • Verdict: native. A struct with named fields is a record. derive generates Debug, Clone and PartialEq.
  • ..ada.clone() takes the remaining fields from a clone. With ..ada, the String field moves into the new value, and ada can no longer be used as a whole.
  • A binding is immutable unless it is declared with mut.
  • Tuples. A product whose parts have positions, not names. Java calls records "nominal tuples".11 See Tuple.
  • Sums of records. A sum type whose cases are records, such as a sealed interface with record cases in Java. See Sum types and Algebraic data type.
  • Classes. A class can hold fields like a record, but it usually hides them behind methods. A record shows its fields.
  • Row polymorphism. A function can accept any record that has at least some fields. See Row polymorphism.
  • Database rows. A row of a table is a record with one field for each column.

Pitfalls

A shallow copy shares a mutable field

A copy with a change copies the fields, not the objects that the fields refer to. Here team_b gets a new name, but its list of members is the same list as in team_a.

This code runs but gives a wrong answer on purpose.

from dataclasses import dataclass, replace


@dataclass(frozen=True)
class Team:
    name: str
    members: list[str]


team_a = Team("A", ["Ada"])
team_b = replace(team_a, name="B")
team_b.members.append("Grace")
print(team_a.members)
Output
['Ada', 'Grace']

frozen=True stops assignment to the fields, but it does not stop a change inside the list. The fix is an immutable field type, such as tuple[str, ...], or a copy of the list: replace(team_a, name="B", members=list(team_a.members)).

Changing a copy of a struct in a loop

In Go, a range loop assigns each element to the loop variable "as in an assignment statement".13 A struct assignment copies the struct, so a change to the loop variable changes only the copy.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

type Person struct {
	Name string
	Age  int
}

func main() {
	people := []Person{{"Ada", 36}, {"Grace", 45}}
	for _, p := range people {
		p.Age++
	}
	fmt.Println(people)
}
Output
[{Ada 36} {Grace 45}]

The ages did not change. The fix is to write through the index: for i := range people { people[i].Age++ }.

Cost

A record stores each field once, plus any padding. Reading a field is a load at a fixed offset. A copy with a change copies every field once, so its cost grows with the number of fields, not with the size of the objects that the fields refer to. A record that is a value type is copied in full on each assignment and each call. A large struct that is passed often can be passed by pointer or by reference.

History

"COBOL was the first widespread programming language to support record types."1 Its records could nest, and its MOVE CORRESPONDING statement copied fields between two records by name.1 ALGOL W, designed by Niklaus Wirth and Tony Hoare, added "reference to record data types" to ALGOL 60.14 "The Pascal programming language was one of the first languages to fully integrate record types with other basic types into a logically consistent type system."1 C provides records as structs.1

Later languages added records that the compiler completes with methods. Python 3.7 added data classes with PEP 557.15 Java records were a preview in JDK 14 and became final in JDK 16.11 C# added the record modifier, and Kotlin has data classes.107

References

  1. Record (computer science), Wikipedia, the introduction; History
  2. The Rust Programming Language, 5.1 Defining and Instantiating Structs, the introduction; Creating Instances with Struct Update Syntax
  3. The Swift Programming Language, Structures and Classes, Memberwise Initializers for Structure Types; Structures and Enumerations Are Value Types
  4. The OCaml Manual, release 5.3, Expressions, 11.7.2 Records (the expression with)
  5. F# language reference, Records, Remarks; Creating Records by Using Record Expressions
  6. C# language reference, with expression, the introduction
  7. Kotlin documentation, Data classes, the introduction (the generated members); Copying
  8. The Python Standard Library, dataclasses, the introduction; replace(); frozen instances
  9. MDN Web Docs, Spread syntax (...), Description
  10. C# fundamentals, Record types, the introduction
  11. JEP 395: Records, the header (Release 16); Summary; History
  12. TypeScript Handbook, Object Types, readonly Properties
  13. The Go Programming Language Specification, For statements with range clause; Comparison operators
  14. ALGOL W, Wikipedia, the infobox; the introduction
  15. PEP 557: Data Classes, the header (Python-Version 3.7); Abstract

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/TGG8Y0/text.yaml