Conceptintro
Composite type
Also called compound type, compound data type, composite data type, aggregate type, derived type, structured type, structured data type, data structure type.
A composite type builds a value from values of other types: arrays, records, tuples, maps, unions, functions and pointers. A type constructor such as list[int] makes it.
- Applies to
- core-languages
Idea
A program seldom works with one number at a time. A point has two coordinates, a person has a name and an age, and a class has a list of students. A composite type puts values of other types together into one value. The parts can have the same type, as in an array of numbers, or different types, as in a record with a name and an age. A part can be composite too, so a list of records that hold lists is still one type.
from dataclasses import dataclass
# Each value below is built from values of other types.
point = (3, 4) # a tuple: two ints, found by position
scores = [90, 85, 77] # a list: many ints, found by index
ages = {"ann": 31, "bob": 27} # a dict: str keys that map to int values
@dataclass
class Person: # a record: named fields of different types
name: str
age: int
tags: list[str]
p = Person("Ann", 31, ["admin"])
print(type(point).__name__, type(scores).__name__, type(ages).__name__, type(p).__name__)
print(point[1], scores[0], ages["bob"], p.name)
# A part can be composite too.
print(p.tags[0], len(p.tags))
# list[str] is a type that a type constructor builds from str.
t = list[str]
print(t, t.__origin__.__name__, t.__args__)
# The record compares part by part.
print(p == Person("Ann", 31, ["admin"]))
tuple list dict Person
4 90 27 Ann
admin 1
list[str] list (<class 'str'>,)
True
The tuple, the list, the dict and the record each hold several values, and the program gets one part by a position, an index, a key or a field name. The field tags of the record is a list, so a composite value can contain other composite values. The expression list[str] is a type, not a value: it is the type constructor list applied to the type str. The last line shows that the generated == of a dataclass compares the fields one by one.
How it works
Built from other types. "In computer science, a composite data type or compound data type is a data type that consists of programming language scalar data types and other composite types that may be heterogeneous and hierarchical in nature"1. A scalar type, such as an integer, a character or a Boolean, has values that the language does not split into parts. C names the two groups: "scalar types: arithmetic types, pointer types, and nullptr_t" and "aggregate types: array types and structure types"2.
The main forms. Most languages have a few forms, and they differ in how a program finds a part:
- An array: "An array is a numbered sequence of elements of a single type, called the element type"3. The program finds an element by an index. See array.
- A record or struct: "A struct is a sequence of named elements, called fields, each of which has a name and a type"3. The program finds a field by its name. See record type.
- A tuple: a record whose parts have positions and no names. In TypeScript, "A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions"4. See tuple.
- A map: "A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type"3. See map and dictionary.
- A union: a value that holds one of several types. In C, "The value of at most one of the members can be stored in a union at any one time"5. A tagged union or a sum type also records which member it holds. See union type.
- A function type and a pointer type: they are built from other types too. In Go, "A function type denotes the set of all functions with the same parameter and result types"3. See pointers and references.
Each language draws its own list. Go says that its composite types, which are array, struct, pointer, function, interface, slice, map and channel types, "may be constructed using type literals"3. C has the derived types: array, structure, union, function, pointer and atomic types2. C++ calls them compound types and lists reference, pointer, array, function, enumeration, class and union types among them6. The Rust Reference lists sequence types (tuple, array and slice), user-defined types (struct, enum and union), function types and pointer types7. Java divides its types into "two kinds: primitive types and reference types", and "There are four kinds of reference types": class types, interface types, type variables and array types8. In Java, every composite value is an object: "An object is a class instance or an array", and "The reference values (often just references) are pointers to these objects"8.
Type constructors. "In the area of mathematical logic and computer science known as type theory, a type constructor is a feature of a typed formal language that builds new types from old ones"9. "Some type constructors take another type as an argument, e.g., the constructors for product types, function types, power types and list types"9. In code, []int and map[string]int in Go, Vec<i32> in Rust, int[] in Java and list[int] in Python apply a type constructor to a type. In Python, such type objects "are generally created by subscripting a class"10. Because the result is a type, it can be an argument again, as in list[tuple[str, int]].
Layout in memory. In C, a struct "is a type consisting of a sequence of members whose storage is allocated in an ordered sequence", and a union is "a type consisting of a sequence of members whose storage overlaps"11. "The size of a struct is at least as large as the sum of the sizes of its members"11, because the compiler can add padding, and "The union is only as big as necessary to hold its largest member"5. A type cannot contain itself directly: in C, "a struct cannot have a member of its own type. A pointer to its own type is allowed, and is commonly used to implement nodes in linked lists or trees"11. See recursive type.
Copy and equality. A composite value that the language stores inline, such as a C struct, a Go array or a C# struct, is copied as a whole on assignment. A composite value behind a reference, such as a Java array or a JavaScript object, is shared, and a change through one name shows through the other. Equality follows the same split. In Go, "Struct types are comparable if all their field types are comparable", but "Slice, map, and function types are not comparable"3. In JavaScript, == on two objects is true "only if both operands reference the same object"12. See value equality and identity.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has object types, array types such as number[], tuple types such as [string, number] and union types. The types describe JavaScript objects and arrays, so the run-time values are the same as in JavaScript. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has classes, data classes with generated equals and copy, Array<T>, Pair and Triple, and the List, Set and Map interfaces. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A row of a table is a record of column values, and a query result is a list of rows. Some databases add composite column types, such as arrays and row types, but support differs. No example file exists. |
| Bash | Idiom | Bash has indexed arrays and associative arrays, but their elements are strings, so an array cannot hold another array or a record. Scripts keep parallel arrays or encode a record in one string. No example file exists. |
| PowerShell | Native | PowerShell has arrays, hashtables and [pscustomobject] for records, and it can use any .NET type, such as List[T] and tuples. No example file exists because pwsh is not installed. |
| HTML | Does not apply | An element can contain other elements, which gives a document its structure, but HTML has no types of values. |
| CSS | Idiom | A shorthand property such as border or font takes a value that combines values of other types, such as a length, a keyword and a color. |
| Regular expressions | Does not apply | A regular expression has groups that collect parts of a match, but the pattern language has no values and no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | tuple, list, dict and set; classes and @dataclass for records; list[int] as a type |
| JavaScript | native | objects and arrays; Map and Set; no separate tuple or record type |
| TypeScript | native | object types, array types such as number[], tuple types such as [string, number], union types |
| Java | native | arrays, classes and records; each composite value is an object behind a reference |
| Kotlin | native | classes, data class, Array<T>, Pair and Triple, and the collection interfaces |
| C# | native | arrays, class, struct, record and tuples such as (int, string) |
| Go | native | arrays, slices, structs, maps, pointers, functions, interfaces and channels |
| Rust | native | tuples, arrays, slices, struct, enum and union; references and Box<T> |
| C | native | arrays, struct, union, pointers and function types |
| C++ | native | arrays, classes, union, references and pointers; std::pair, std::tuple and std::array |
| Bash | idiom | indexed and associative arrays of strings; an array cannot hold another array |
| PowerShell | native | arrays, hashtables and [pscustomobject]; all .NET types |
| SQL | idiom | a table row is a record of column values; some databases add composite column types |
| Regex | n/a | a pattern has groups, but no values and no types |
| HTML | n/a | elements nest inside elements, but HTML has no types of values |
| CSS | idiom | a shorthand property such as border takes a value built from values of other types |
Every general-purpose language has arrays and some form of record, so the verdict is native for all of them except Bash, where an array holds only strings. The languages differ in which forms they build in, in whether a composite value is stored inline or behind a reference, and in what == means for it.
The example files show these differences. Python shows that * on a list of lists repeats one inner list, that tuples compare part by part, and that a frozen dataclass rejects a change. JavaScript shows that === compares objects by reference, that a spread copy shares the inner array, and that structuredClone makes a deep copy. Java compares arrays with == and Arrays.equals and shows that a record compares by value. C# shows that tuples and structs are copied and classes are shared. Go copies arrays and structs, compares them with ==, and shares the storage of a slice. Rust builds a tuple, an array, a struct, an enum with data and a recursive list with Box. C shows padding, the size of a union, the copy of a struct and a linked list through a pointer. C++ uses std::pair, std::tuple, std::array and a struct with a defaulted ==.
from dataclasses import dataclass
# A grid is a list of lists. * repeats the reference to one inner list.
bad = [[0] * 3] * 3
bad[0][0] = 1
print(bad)
good = [[0] * 3 for _ in range(3)]
good[0][0] = 1
print(good)
# Tuples compare part by part, from the left.
print((1, "a") == (1, "a"), (1, "a") < (1, "b"))
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
print(p, p == Point(1, 2), hash(p) == hash(Point(1, 2)))
try:
p.x = 5
except AttributeError as e:
print(type(e).__name__)
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
True True
Point(x=1, y=2) True True
FrozenInstanceError
- Verdict: native.
[[0] * 3] * 3holds three references to one inner list, so a change to one row shows in all rows. A list comprehension makes a separate list for each row. Tuples compare part by part. A frozen dataclass compares and hashes by its fields and raisesFrozenInstanceError, a subclass ofAttributeError, when code assigns to a field.
#include <array>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
struct Person {
std::string name;
int age;
bool operator==(const Person&) const = default;
};
int main() {
std::pair<int, std::string> pr{1, "a"};
std::tuple<int, double, char> tp{2, 3.5, 'x'};
std::cout << pr.second << ' ' << std::get<1>(tp) << ' ' << std::tuple_size_v<decltype(tp)> << '\n';
auto [n, s] = pr; // a structured binding takes the pair apart
std::cout << n << s << '\n';
std::array<int, 3> a{1, 2, 3};
auto b = a; // std::array copies like a value
b[0] = 9;
std::cout << a[0] << ' ' << (a == std::array<int, 3>{1, 2, 3}) << '\n';
Person p{"Ann", 31};
Person q = p;
q.age = 32;
std::cout << p.age << ' ' << (p == Person{"Ann", 31}) << '\n';
std::vector<Person> people{p, q};
std::cout << people.size() << ' ' << people[1].age << '\n';
}
a 3.5 3
1a
1 1
31 1
2 32
- Verdict: native.
std::pairandstd::tupleare tuples from the library, andstd::getand a structured binding take them apart.std::arrayis a fixed-size array that copies and compares like a value, unlike a built-in array. A struct copies its members on assignment, and a defaultedoperator==compares them one by one.std::vector<Person>holds the records themselves, not pointers to them.
import java.util.Arrays;
import java.util.List;
public class Main {
record Point(int x, int y) {}
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println((a == b) + " " + Arrays.equals(a, b));
Point p = new Point(1, 2);
System.out.println(p + " " + p.equals(new Point(1, 2)) + " " + (p == new Point(1, 2)));
int[][] grid = new int[2][3];
grid[0][1] = 7;
System.out.println(Arrays.deepToString(grid));
List<Point> points = List.of(p, new Point(3, 4));
System.out.println(points.get(1).y());
int[] c = a;
c[0] = 99;
System.out.println(a[0]);
}
}
false true
Point[x=1, y=2] true false
[[0, 7, 0], [0, 0, 0]]
4
99
- Verdict: native. Arrays, classes and records are reference types, so
==compares references andArrays.equalscompares the elements. A record getsequals,hashCodeandtoStringfrom its components, so two points with the same coordinates are equal, but they are two objects.int[][]is an array of arrays.c = acopies the reference, so a change throughcshows ina.
#include <stdio.h>
#include <string.h>
struct point { int x; int y; };
struct mixed { char c; int i; char d; };
union number { int i; float f; };
struct node { int value; struct node *next; };
int main(void) {
struct point p = { 1, 2 };
struct point q = p; /* assignment copies the struct */
q.x = 5;
printf("%d %d\n", p.x, q.x);
/* Padding: the size can be more than the sum of the members. */
printf("%zu %zu\n", sizeof(struct mixed), 2 * sizeof(char) + sizeof(int));
/* A union is as large as its largest member. */
printf("%zu\n", sizeof(union number));
int a[3] = { 1, 2, 3 };
int b[3];
memcpy(b, a, sizeof a); /* an array cannot be assigned, so copy its bytes */
printf("%zu %d\n", sizeof a / sizeof a[0], b[2]);
/* A struct can point to its own type. */
struct node second = { 2, NULL };
struct node first = { 1, &second };
for (struct node *n = &first; n != NULL; n = n->next) {
printf("%d\n", n->value);
}
return 0;
}
1 5
12 6
4
3 3
1
2
- Verdict: native. Assignment copies a struct, but C has no
==for structs and no assignment for arrays, so the program copies an array withmemcpy. On this compiler,struct mixedtakes 12 bytes for 6 bytes of members, because the compiler alignsint iand pads the end. The union takes the 4 bytes of its largest member.struct nodeholds a pointer to its own type, which makes a linked list.
using System;
// A tuple is a value type, so assignment copies it.
var t1 = (Name: "Ann", Age: 31);
var t2 = t1;
t2.Age = 32;
Console.WriteLine(t1.Age + " " + t2.Age);
Console.WriteLine(t1 == ("Ann", 31));
// A struct is copied, and a class is shared.
var s1 = new PointS { X = 1 };
var s2 = s1;
s2.X = 5;
var c1 = new PointC { X = 1 };
var c2 = c1;
c2.X = 5;
Console.WriteLine(s1.X + " " + c1.X);
// A record compares by value.
var r = new PointR(1, 2);
Console.WriteLine(r + " " + (r == new PointR(1, 2)));
// Arrays are reference types.
int[] a = { 1, 2 };
int[] b = a;
b[0] = 9;
Console.WriteLine(a[0]);
struct PointS { public int X; }
class PointC { public int X; }
record PointR(int X, int Y);
31 32
True
1 5
PointR { X = 1, Y = 2 } True
9
- Verdict: native. A tuple and a
structare value types, sot2ands2are copies, and a change to them does not changet1ands1. Aclassis a reference type, soc1andc2are one object. Arecordis a class with value equality and a generatedToString. Arrays are reference types, as in Java.
// An object is a record with named properties, and an array holds items by index.
const p = { name: "Ann", age: 31, tags: ["admin"] };
console.log(typeof p, Array.isArray(p.tags), p.tags.length);
// === compares objects by reference, not by contents.
const a = [1, 2];
const b = [1, 2];
console.log(a === b, a === a, JSON.stringify(a) === JSON.stringify(b));
// A spread copy is shallow: the inner array is shared.
const q = { ...p };
q.name = "Bob";
q.tags.push("dev");
console.log(p.name, p.tags);
// structuredClone makes a deep copy.
const r = structuredClone(p);
r.tags.push("ops");
console.log(p.tags.length, r.tags.length);
// A Map takes keys of any type, and it compares object keys by reference.
const m = new Map([[a, "first"]]);
console.log(m.get(a), m.get(b));
object true 1
false true true
Ann [ 'admin', 'dev' ]
2 3
first undefined
- Verdict: native. Objects and arrays are the composite values of JavaScript, and
typeofgives"object"for both.===is true only for the same object, so two arrays with the same items are not equal. A spread copy gets its ownname, but it shares the array intags.structuredClonecopies the inner array too. AMapfinds an object key by reference, sobdoes not find the entry ofa.
package main
import (
"fmt"
"slices"
)
type Point struct {
X, Y int
}
func main() {
// Arrays and structs are values: assignment copies them, and == compares the parts.
a := [3]int{1, 2, 3}
b := a
b[0] = 9
fmt.Println(a, b, a == [3]int{1, 2, 3})
p := Point{1, 2}
q := p
q.X = 5
fmt.Println(p, q, p == Point{1, 2})
// A slice refers to an array that its copies share.
s := []int{1, 2, 3}
t := s
t[0] = 9
fmt.Println(s, slices.Equal(s, t))
m := map[string][]int{"a": {1}}
m["a"] = append(m["a"], 2)
fmt.Println(m)
// A type literal builds a composite type without a name.
pairs := []struct {
K string
V int
}{{"x", 1}, {"y", 2}}
fmt.Printf("%v %T\n", pairs[1], pairs[1])
}
[1 2 3] [9 2 3] true
{1 2} {5 2} true
[9 2 3] true
map[a:[1 2]]
{y 2} struct { K string; V int }
- Verdict: native. An array and a struct are values, so
bandqare copies, and==compares them part by part. A slice is a view of an array, sotandsshare the elements. Go has no==for slices, so the example usesslices.Equal.[]struct{ K string; V int }is a slice of an anonymous struct type that a type literal builds.
#[derive(Debug, Clone, PartialEq)]
struct Person {
name: String,
age: u32,
}
#[derive(Debug)]
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
}
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
fn main() {
let t: (i32, &str) = (1, "a");
let arr: [u8; 3] = [1, 2, 3];
println!("{:?} {} {:?} {}", t, t.1, arr, std::mem::size_of::<[u8; 3]>());
let p = Person { name: String::from("Ann"), age: 31 };
let q = p.clone();
println!("{:?} {}", q, p == q);
let shapes = [Shape::Circle(1.0), Shape::Rect { w: 2.0, h: 3.0 }];
for s in &shapes {
let area = match s {
Shape::Circle(r) => 3.0 * r * r,
Shape::Rect { w, h } => w * h,
};
println!("{:?} {}", s, area);
}
// A recursive type needs a pointer such as Box, so its size is known.
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{:?}", list);
}
(1, "a") a [1, 2, 3] 3
Person { name: "Ann", age: 31 } true
Circle(1.0) 3
Rect { w: 2.0, h: 3.0 } 6
Cons(1, Cons(2, Nil))
- Verdict: native. A tuple finds its parts by position, such as
t.1, and an array of 3 bytes has a size of 3 bytes. Astructgets==and a copy only when it derivesPartialEqandClone. Anenumholds one of its variants, each with its own data, andmatchtakes it apart. The recursiveListholds the next node in aBox, because a type that contains itself directly would have no finite size.
Variations and related ideas
- Product and sum types. A record or a tuple holds all its parts at once, and a sum type holds one of its variants. Together they are the algebraic data types. See product type and sum types.
- Collections. A list, a set and a map hold any number of items of one type. A record or a tuple holds a fixed number of parts, often of different types.
- Recursive types. A list node that points to the next node, or a tree whose children are trees, is a composite type that refers to itself through a pointer or a reference. See recursive type.
- Generic types.
List<T>in Java andVec<T>in Rust are type constructors that the program applies to many element types. See parametric polymorphism. - Named and anonymous types. A Go type literal such as
struct { X, Y int }or a TypeScript object type has no name of its own. Aclassor arecorddeclaration gives the type a name.
Pitfalls
- A copy that shares its parts. In Python,
[[0] * 3] * 3makes one inner list and three references to it, because "items in the sequence s are not copied; they are referenced multiple times"10. A change togrid[0][0]changes every row. A spread copy in JavaScript andcopy.copyin Python are shallow in the same way. ==compares references. In Java,a == bon two arrays is true only for the same array.Arrays.equalscompares the contents: "Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal"13. In JavaScript, there is no built-in deep equality for objects. In Go,==on two slices does not compile.- A value type that is copied. C# says that "Tuple types are value types; tuple elements are public fields. That design makes tuples mutable value types"14. A change to a copy of a tuple or a struct does not change the original. That is correct, but it surprises a programmer who expects a shared object.
- Equality of records that are not value records. A Python class compares by identity unless it defines
__eq__. A dataclass adds one that "compares the class by comparing each field in order"15. A Java record and a C# record do the same, but a plain class does not. - Padding and layout.
sizeofof a C struct can be more than the sum of its members11, so code that writes a struct to a file or a network byte by byte depends on the compiler. Write each field instead. - The wrong member of a union. A C union holds one member at a time5. Reading another member gives the bytes of the last one written. Keep a tag next to the union, or use a sum type.
Cost
An array or a struct of value types keeps its parts next to each other in one block of memory, and the program finds a part at an offset that the compiler knows. In Java, JavaScript and Python, a composite value is an object behind a reference, and each part that is an object is another reference, so a list of points is a list of pointers to separate objects. That costs an allocation for each object and one more memory read for each part. A copy of a large value type copies all its bytes, so code passes a large struct by pointer or by reference. A union costs only the size of its largest member5, and padding can make a struct larger than its members11.
History
Records came from data processing. According to Wikipedia, "COBOL was the first widespread programming language to support record types"16, and "COBOL's design was started in 1959 by CODASYL"17. "The early languages developed for numeric computing, such as FORTRAN (up to FORTRAN IV) and ALGOL 60, did not support record types"16. Later, "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"16, and "The C language provides the record concept using structs"16. Records as a short form for data classes came much later: "Java introduced records in Java 17"16.
References
- Composite data type, Wikipedia, Introduction
- Type, C reference, cppreference.com, Type classification; Type groups
- The Go Programming Language Specification, Types; Array types; Struct types; Map types; Function types; Comparison operators
- Object Types, The TypeScript Handbook, Tuple Types
- Union declaration, C reference, cppreference.com, Explanation
- Fundamental and compound types, C++ reference, cppreference.com, Type classification
- Types, The Rust Reference, Introduction; Type kinds
- The Java Language Specification, Java SE 25 Edition, Chapter 4, 4.3 Reference Types and Values; 4.3.1 Objects
- Type constructor, Wikipedia, Introduction
- Built-in Types, Python 3.14 documentation, Common Sequence Operations, note 2; Generic Alias Type
- Struct declaration, C reference, cppreference.com, Explanation
- Equality (==), MDN Web Docs, Description
- Java SE 25 API, Class Arrays, equals(int[], int[])
- Tuple types, C# language reference, Introduction
- dataclasses, Python 3.14 documentation, @dataclass, the eq parameter
- Record (computer science), Wikipedia, History
- COBOL, Wikipedia, Introduction
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 E4HT1G Edit this page History Report an error Markdown