Struct in F# is a new Custom Value data type created with a combination of multiple Inbuilt native types.
Variables created using struct type hold values of different data types.
How to declare Struct and variables
F# defined two syntaxes for declaring struct type
type [modifier] type-name =
struct
type-definition-elements-and-members
end
or
[<StructAttribute>]
type [modifier] type-name =
type-definition-elements-and-members
Type
is a keywordModifier
is a standard access modifier and visibility to access.type-name is a new type, used for creating a variables
struct
,end
, andStructAttribute
are keywords.if
struct
, andend
syntax is used,StructAttribute
syntax can be skippedtype-definition-elements-and-members contains the following things
- Member declarations and definitions fields
- Constructors with zero or parameterized syntax
- Mutable and Immutable fields
- Interfaces
Contains member declaration using
val
, does not support let.val
variables can have a field name and datatype, not initialized with default, and contain default value null or zero.Explicit Constructor contains logic to initialize fields or members
F# Struct Example
The below Struct code contains the following things
- Struct definition
- Members declared with
val
, field names, and datatypes - Constructor defined using new, initialized with all fields
- Create a Variable using a new struct type
- Accessed struct members using type. membername syntax.
type Employee = struct
val id : int
val name: string
val salary : int
new (id, name, salary) = // Constructor definition
{id = id; name = name; salary = salary;}
end
let employee1 = new Employee(1,"john", 5000) // constructor called
printfn "Id : %i " employee1.id
printfn "Name : %s" employee1.name
printfn "Salary : %i" employee1.salary
Readonly Struct example
F# also defined readonly structs that contain code for readonly properties,
Mark the struct annotation as IsReadOnly
. It contains immutable variables only.
Throws an error if mutable variables are used.
[<IsReadOnly; Struct>]
type print (first: int, second: int) =
member x.first = first
member x.second = second
Difference between Classes and Struct
It is similar to class to hold data and behavior for a small set of data.
Classes are reference types and Struct are value types that store the data on Stack.
Classes support inheritance. Struts do not support inheritance. Classes contain let or do bindings, Structs do not support let or do binding