FS0005: This field is not mutable
This message is given when a record field is mutably assigned, but the record field is not marked mutable.
In the following code, a record with immutable fields is declared, an instance of that record is created, and a field of that record is mutably assigned, showing the error:
type Food = { Kind: string
DaysOld: int }
let apple = { Kind = "apple"
DaysOld = 10 }
apple.Kind <- "orange"
This code results in the following output:
error FS0005: This field is not mutable
Here, the immutable record field Kind
was assigned the string value "orange", but F# doesn't support mutable assignment unless the field is explicitly marked that way.
To solve this message you have to change either the way the field is defined, or how you're setting the new value.
If you actually intended for the record to have a mutable field (which is a fairly rare practice) you can mark the field as mutable
in the type definition, as shown here:
type Food = { mutable Kind: string
DaysOld: int }
let apple = { Kind = "apple"
DaysOld = 10 }
apple.Kind <- "orange"
However, it is more idiomatic in F# to perform an immutable update of a record via the with
expression, which creates a copy of the original record with the fields you specified set to new values as shown here:
type Food = { Kind: string
DaysOld: int }
let apple = { Kind = "apple"
DaysOld = 10 }
let orange = { apple with Kind = "orange" }