Structs in F#

Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This person struct type has name and age fields.

type Person = {
    Name: string
    Age: int
}

newPerson constructs a new person struct with the given name.

let newPerson name =
    { Name = name; Age = 42 }

F# uses garbage collection; you can safely return a newly created object - it will only be cleaned up by the garbage collector when there are no active references to it.

let main argv =
    // This syntax creates a new struct.
    printfn "%A" { Name = "Bob"; Age = 20 }

    // You can name the fields when initializing a struct.
    printfn "%A" { Name = "Alice"; Age = 30 }

    // Omitted fields will be zero-valued.
    printfn "%A" { Name = "Fred"; Age = 0 }

    // A `newPerson` function to create a new person.
    printfn "%A" (newPerson "Jon")

    // Access struct fields with dot notation.
    let s = { Name = "Sean"; Age = 50 }
    printfn "%s" s.Name

    // Structs are mutable.
    let mutable sp = s
    sp <- { sp with Age = 51 }
    printfn "%d" sp.Age

    // Anonymous struct type.
    let dog = { Name = "Rex"; IsGood = true }
    printfn "%A" dog

    0 // Return an integer exit code

To run the code, compile and execute with your preferred F# compiler.

$ fsharpc Structs.fs
$ mono Structs.exe

Output:

$ mono Structs.exe
{ Name = "Bob"
Age = 20 }
{ Name = "Alice"
Age = 30 }
{ Name = "Fred"
Age = 0 }
{ Name = "Jon"
Age = 42 }
Sean
50
51
{ Name = "Rex"
IsGood = true }

An anonymous type can be used when a struct definition is only needed for a single use case, like in table-driven tests.

Now that we can work with structs in F#, let’s learn more about the language.