Type Declarations
Q# supports user-defined types. User-defined types are similar to record types in F#; they are immutable but support a copy-and-update construct.
User-defined types
User-defined types may contain both named and anonymous items.
The following declaration within a namespace, for example, defines a type Complex
which has two named items Real
and Imaginary
, both of type Double
:
newtype Complex = (Real: Double, Imaginary : Double);
Any combination of named and unnamed items is supported, and inner items may also be named.
For example, the type Nested
, defined as
newtype Nested = (Double, (ItemName : Int, String));
contains two anonymous items of type Double
and String
respectively, and a named item ItemName
of type Int
.
You can access the contained items via their name or by deconstruction (for more information, see item access). You can also access a tuple of all items where the shape matches the one defined in the declaration via the unwrap operator.
User-defined types are useful for two reasons. First, as long as the libraries and programs that use the defined types access items via their name rather than by deconstruction, the type can be extended to contain additional items later on without breaking any library code. Because of this, accessing items via deconstruction is generally discouraged.
Second, Q# allows you to convey the intent and expectations for a specific data type since there is no automatic conversion between values of two user-defined types, even if their item types are identical.
User-defined constructors
Constructors for user-defined types are automatically generated by the compiler. Currently, it is not possible to define a custom constructor, though this may be an addition to the language in the future.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for