ZetCode

F# struct types

last modified December 2, 2026

In this article we work with struct types, which are value types.

Records, tuples, unions, and options are reference types. A value of such a type lives on the heap, and a variable holds a reference to it. A struct is a value type: the variable, the list node, or the array slot holds the data itself. Small structs save memory allocations and are faster to create, which matters in code that creates millions of values, such as numeric or graphics code. Larger structs are copied on every assignment and function call, so structs are best kept small. Most F# types become structs with the [<Struct>] attribute. How values and references are copied is explained in F# copy by value and reference.

A struct record

A record becomes a struct when its type definition is marked with the [<Struct>] attribute. It is created and used like any other record.

struct_record.fsx
[<Struct>]
type Point = { X: float; Y: float }

let p = { X = 2.5; Y = -1.0 }
let q = { p with Y = 4.0 }

printfn "%A" q
printfn "%b" (p = { X = 2.5; Y = -1.0 })
printfn "%b" (typeof<Point>.IsValueType)

We define a point as a struct record.

[<Struct>]
type Point = { X: float; Y: float }

The attribute goes on its own line above the type, or before type on the same line. Copy and update expressions, structural equality, and patterns work as with ordinary records.

printfn "%b" (typeof<Point>.IsValueType)

typeof returns the .NET type of Point, which reports that it is a value type.

λ dotnet fsi struct_record.fsx
{ X = 2.5
  Y = 4.0 }
true
true

The size of a struct

The sizeof function returns the number of bytes a value of a type takes in a variable or an array slot.

sizes.fsx
type PointRef = { X: float; Y: float }

[<Struct>]
type PointVal = { X: float; Y: float }

printfn "int: %d" sizeof<int>
printfn "float: %d" sizeof<float>
printfn "reference record: %d" sizeof<PointRef>
printfn "struct record: %d" sizeof<PointVal>

let refs = Array.init 1000 (fun i -> { PointRef.X = float i; Y = 0.0 })
let vals = Array.init 1000 (fun i -> { PointVal.X = float i; Y = 0.0 })
printfn "last x: %.1f %.1f" refs[999].X vals[999].X

We compare the two forms of a point.

printfn "reference record: %d" sizeof<PointRef>
printfn "struct record: %d" sizeof<PointVal>

For a reference type sizeof gives the size of the reference, 8 bytes on a 64-bit system. The record itself is stored elsewhere, in a separate heap object with a header. The struct record holds its two floats directly, 16 bytes.

let refs = Array.init 1000 (fun i -> { PointRef.X = float i; Y = 0.0 })
let vals = Array.init 1000 (fun i -> { PointVal.X = float i; Y = 0.0 })

The refs array holds 1000 references to 1000 separate objects; the vals array holds the 1000 points themselves in one block of memory. The labels are qualified with the type name, since both records have the same fields. Arrays are covered in F# array.

λ dotnet fsi sizes.fsx
int: 4
float: 8
reference record: 8
struct record: 16
last x: 999.0 999.0

Changing a struct

A struct can have mutable fields, but a struct value can only be changed when the binding that holds it is mutable too. The value is the data itself, so changing a field changes the binding.

mutate.fsx
[<Struct>]
type Counter = { mutable Count: int }

let counter = { Count = 0 }
counter.Count <- counter.Count + 1

We try to increment a counter bound with a plain let.

counter.Count <- counter.Count + 1

The compiler rejects the assignment. With a reference record the same code would work, because the binding holds only a reference and the object it points to is changed. Declaring the binding with let mutable counter fixes the error. Mutable fields are covered in F# mutability.

λ dotnet fsi mutate.fsx
mutate.fsx(5,1): error FS0256: A value must be mutable in order to mutate the contents or take the address of a value type, e.g. 'let mutable x = ...'

Struct tuples

A tuple written with the struct keyword is a value type. Struct tuples avoid an allocation when a function returns several values.

struct_tuples.fsx
let divRem a b = struct (a / b, a % b)

let struct (q, r) = divRem 17 5
printfn "%d rest %d" q r

let pair = struct ("falcon", 6)
printfn "%A" pair

let describe (struct (name: string, length: int)) =
    $"{name} has {length} letters"

printfn "%s" (describe pair)

match divRem 12 4 with
| struct (_, 0) -> printfn "12 is divisible by 4"
| struct (_, rest) -> printfn "rest %d" rest

We return, take apart, and match struct tuples.

let divRem a b = struct (a / b, a % b)

The function has type int -> int -> struct (int * int).

let struct (q, r) = divRem 17 5

A struct tuple is taken apart with a pattern that also starts with struct. The two kinds of tuples are different types: a struct tuple cannot be passed where a reference tuple is expected, and the compiler reports that one tuple type is a struct tuple and the other a reference tuple.

λ dotnet fsi struct_tuples.fsx
3 rest 2
struct ("falcon", 6)
falcon has 6 letters
12 is divisible by 4

Struct unions

A discriminated union can be a struct as well. The value then holds the tag of the case and the fields of the cases directly, so the union is best suited for a few small cases.

struct_union.fsx
[<Struct>]
type Shape =
    | Circle of radius: float
    | Rect of width: float * height: float

let area shape =
    match shape with
    | Circle r -> System.Math.PI * r * r
    | Rect (w, h) -> w * h

let shapes = [ Circle 1.0; Rect (2.0, 3.5); Circle 0.5 ]

for s in shapes do
    printfn "%A: %.2f" s (area s)

printfn "%b" (typeof<Shape>.IsValueType)

A shape is either a circle or a rectangle.

[<Struct>]
type Shape =
    | Circle of radius: float
    | Rect of width: float * height: float

The cases are matched like the cases of any union. Unions are covered in F# discriminated unions.

λ dotnet fsi struct_union.fsx
Circle 1.0: 3.14
Rect (2.0, 3.5): 7.00
Circle 0.5: 0.79
true

Value options

The voption type is a struct version of option. Its cases are ValueSome and ValueNone, and the ValueOption module has the same functions as the Option module.

voption.fsx
let tryDivide (a: int) (b: int) =
    if b = 0 then ValueNone else ValueSome (a / b)

for b in [4; 0] do
    match tryDivide 20 b with
    | ValueSome n -> printfn "20 / %d = %d" b n
    | ValueNone -> printfn "20 / %d is undefined" b

tryDivide 21 3
|> ValueOption.map (fun n -> n * 10)
|> ValueOption.defaultValue -1
|> printfn "%d"

let found = [3; 8; 12] |> List.tryFind (fun x -> x > 5)
printfn "%A" (ValueOption.ofOption found)

A division that may fail returns a value option.

let tryDivide (a: int) (b: int) =
    if b = 0 then ValueNone else ValueSome (a / b)

The function has type int -> int -> int voption. A ValueSome is not allocated on the heap, which helps in functions called very often.

printfn "%A" (ValueOption.ofOption found)

ValueOption.ofOption converts an ordinary option, and ValueOption.toOption converts back.

λ dotnet fsi voption.fsx
20 / 4 = 5
20 / 0 is undefined
70
ValueSome 8

Structs with constructors

A struct can also be declared like a class, with constructor parameters and members. Such a struct always has a second, parameterless constructor that sets every field to its default value: zero, false, or null.

money.fsx
[<Struct>]
type Money(amount: decimal, currency: string) =
    member _.Amount = amount
    member _.Currency = currency
    member m.Add(other: Money) = Money(m.Amount + other.Amount, m.Currency)
    member m.Text = $"{m.Amount:F2} {m.Currency}"

let price = Money(12.50m, "EUR")
let shipping = Money(4.90m, "EUR")

printfn "%s" (price.Add(shipping)).Text

let empty = Money()
printfn "%M" empty.Amount
printfn "%b" (isNull empty.Currency)

A money value stores an amount and a currency code.

[<Struct>]
type Money(amount: decimal, currency: string) =
    member _.Amount = amount

The parameters after the type name form the constructor, and the members read them. The underscore stands for the value the member is called on when the member does not need it. Constructors and members are covered in F# classes.

let empty = Money()

The default constructor skips our parameters. The amount is zero and the currency is null, which code using Money must be prepared for. Struct records and struct unions have default values too, but they cannot be created this way by accident.

λ dotnet fsi money.fsx
17.40 EUR
0
true

The limits of structs

A struct holds its fields directly, so a struct cannot contain a field of its own type. The size of such a value would be infinite.

cyclic.fsx
[<Struct>]
type Node = { Value: int; Next: Node }

We try to define a linked list node as a struct record.

type Node = { Value: int; Next: Node }

The compiler reports a cyclic reference. Without the attribute the record would compile, since the field would then be a reference. A field of type Node option also works, because an option is a reference type. For the same reason recursive data such as trees is built from reference types.

λ dotnet fsi cyclic.fsx
cyclic.fsx(2,6): error FS0954: This type definition involves an immediate cyclic reference through a struct field or inheritance relation

A projectile simulation

In the last example a struct record holds a two-dimensional vector. A simple simulation of a thrown ball creates a new position and velocity in every step; with structs, none of these values is allocated on the heap.

projectile.fsx
[<Struct>]
type Vec = { X: float; Y: float }

let add a b = { X = a.X + b.X; Y = a.Y + b.Y }
let scale k v = { X = k * v.X; Y = k * v.Y }

let gravity = { X = 0.0; Y = -9.81 }
let dt = 0.1

let step struct (pos, vel) =
    let vel2 = add vel (scale dt gravity)
    let pos2 = add pos (scale dt vel2)
    struct (pos2, vel2)

let mutable state = struct ({ X = 0.0; Y = 0.0 }, { X = 8.0; Y = 12.0 })
let mutable t = 0.0
let mutable flying = true

while flying do
    state <- step state
    t <- t + dt
    let struct (pos, _) = state
    if pos.Y < 0.0 then
        flying <- false
        printfn "landed after %.1f s at x = %.2f m" t pos.X
    elif int (round (t * 10.0)) % 5 = 0 then
        printfn "t = %.1f s: x = %5.2f, y = %5.2f" t pos.X pos.Y

The position and velocity are updated with the explicit Euler method until the ball falls below the ground.

let step struct (pos, vel) =
    let vel2 = add vel (scale dt gravity)
    let pos2 = add pos (scale dt vel2)
    struct (pos2, vel2)

The step function takes the state as a struct tuple of two struct records and returns a new one. First gravity changes the velocity, then the velocity changes the position.

elif int (round (t * 10.0)) % 5 = 0 then

The time is a float, so it is rounded to tenths before we check that it is a multiple of half a second; the state is printed at those times.

λ dotnet fsi projectile.fsx
t = 0.5 s: x =  4.00, y =  4.53
t = 1.0 s: x =  8.00, y =  6.60
t = 1.5 s: x = 12.00, y =  6.23
t = 2.0 s: x = 16.00, y =  3.40
landed after 2.4 s at x = 19.20 m

Source

F# language reference: Structs

F# language reference: Records

F# language reference: Value options

In this article we have worked with value types: struct records and their size, mutable structs, struct tuples, struct unions, value options, structs with constructors and their default values, and the limits of structs. Named integer constants, which are value types as well, are covered in F# enum type, and converting a struct to obj in F# boxing and unboxing.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.