-
Notifications
You must be signed in to change notification settings - Fork 97
Q# Structs
Q# structs are a way to organize your code. 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, where as 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.
Structs can be declared in the same scopes as callables by using the struct
keyword. They have a name and use curly braces to list our named fields.
struct Foo {
First : Int,
Second : Double,
}
To construct a declared struct, use the new
keyword with the struct type 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;