-
Notifications
You must be signed in to change notification settings - Fork 90
Q# Structs
Q# structs help you structure and organize your data into custom types that aggregate multiple values. They're sometimes called product types or records in other languages. Structs contain named fields that can be accessed and modified.
Structs are declared using the struct
keyword. Consider the following example:
struct Foo {
First : Int,
Second : Double,
}
This defines a struct named Foo
, with two fields: First
of type Int
and Second
of type Double
.
To construct, or instantiate, a struct, use the new
keyword with the struct name and curly braces to list out the field assignments.
let foo = new Foo { First = 3, Second = 4.5 };
There is also a copy-constructor syntax that is very similar to the regular constructor syntax. When listing field assignments, you first list the existing struct object to copy from preceded by ...
. When copying, you only list out the field assignments you want to change during the copying.
let bar = new Foo { ...foo, Second = 6.5 };
To access the field members of a struct object, the .
operator is used.
let x = bar.First;
Structs will be a replacement for newtype
UDT's in the long term, but for now, both are available. Structs differ from UDT's in that they are required to have all of their fields named, and structs are a flat data structure, whereas UDT's could have multiple layers of depth. In this way, structs are intended to be simpler and easier to work than UDT's and encourage cleaner Q# code.