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)
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
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Idiom | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | A 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. |
| SQL | Native | A row of a table is a record with one field for each column. |
| Bash | Idiom | Bash has no record type, but an associative array can hold one key for each field. |
| PowerShell | Idiom | A pscustomobject or a class holds named properties; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no types. |
| CSS | Does not apply | Style rules have no types. |
| Regular expressions | Does not apply | A 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
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")
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. replacemakes a new object and leaves the original unchanged.frozen=Truemakes an assignment to a field raiseFrozenInstanceError.
#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";
}
name: Ada age: 36
copy: Person{Ada, 37}
original: Person{Ada, 36}
same fields equal: yes
- Verdict: native. A
structwith public members is an aggregate, a record that brace initialization fills. - A defaulted
operator==(C++20) compares the members in order. - Copying a
Personcopies thestd::stringtoo, so the copy shares nothing with the original.
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))));
}
}
name: Ada age: 36
copy: Person[name=Ada, age=37]
original: Person[name=Ada, age=36]
same fields equal: yes
- Verdict: native. A
recordgets a private final field and a public accessor for each component, and generatedequals,hashCodeandtoString. - Java has no copy-with-change syntax, so the record declares a
withAgemethod 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;
}
name: Ada age: 36
copy: {name=Ada, age=37}
original: {name=Ada, age=36}
same fields equal: yes
- Verdict: native. A
structis a record. Designated initializers such as.age = 36set fields by name. - C has no
==for structs, soperson_equalcompares the members. It compares the strings withstrcmp, not the pointers. - The copy is shallow:
older.namepoints to the same characters asada.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);
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
recordgets init-only properties, value equality, a formattedToStringand support forwith. withmakes a new object. The original keeps its age.- A
recordis a reference type, but==compares the members.record structmakes a value type.
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));
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.freezestops later changes to the properties. - The spread
...adacopies the properties into a new object, and the laterageoverrides the copied one. ===compares identity, so record equality needs a function that compares the fields.
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));
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
readonlyfields describes an immutable record. The type checker refusesada.age = 40. readonlyexists only at type-checking time. The program at run time is plain JavaScript.- Object types are structural: any object with a
namestring and anagenumber is aPerson.
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}))
}
name: Ada age: 36
copy: {Name:Ada Age:37}
original: {Name:Ada Age:36}
same fields equal: yes
- Verdict: native. A
structis 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.
#[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));
}
name: Ada age: 36
copy: Person { name: "Ada", age: 37 }
original: Person { name: "Ada", age: 36 }
same fields equal: yes
- Verdict: native. A
structwith named fields is a record.derivegeneratesDebug,CloneandPartialEq. ..ada.clone()takes the remaining fields from a clone. With..ada, theStringfield moves into the new value, andadacan no longer be used as a whole.- A binding is immutable unless it is declared with
mut.
Variations and related ideas
- 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)
['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)
}
[{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
- Record (computer science), Wikipedia, the introduction; History
- The Rust Programming Language, 5.1 Defining and Instantiating Structs, the introduction; Creating Instances with Struct Update Syntax
- The Swift Programming Language, Structures and Classes, Memberwise Initializers for Structure Types; Structures and Enumerations Are Value Types
- The OCaml Manual, release 5.3, Expressions, 11.7.2 Records (the expression with)
- F# language reference, Records, Remarks; Creating Records by Using Record Expressions
- C# language reference, with expression, the introduction
- Kotlin documentation, Data classes, the introduction (the generated members); Copying
- The Python Standard Library, dataclasses, the introduction; replace(); frozen instances
- MDN Web Docs, Spread syntax (...), Description
- C# fundamentals, Record types, the introduction
- JEP 395: Records, the header (Release 16); Summary; History
- TypeScript Handbook, Object Types, readonly Properties
- The Go Programming Language Specification, For statements with range clause; Comparison operators
- ALGOL W, Wikipedia, the infobox; the introduction
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag TGG8Y0 Edit this page History Report an error Markdown