Structs are similar to classes but more limited in ways that make them suitable
for representing lightweight value-container-only objects ( like a Point or Rectangle).
Unlike classes (reference type) they are a value type and they cannot be inherited or inherit
from another class or struct.
Other differences from classes:
- Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
- A struct may not declare a default constructor (a constructor without parameters) or a destructor.
- Structs can only declare constructors that have parameters.
- Structs are copied on assignment and when passed into methods.
When a struct is assigned to a new variable or passed to a method, all the data is copied, and any modification to the
new copy does not change the data for the original copy.
- A struct can implement interfaces.
- A struct can be used as a nullable type and can be assigned a null value.
Structures and their contained instance members are public by default though this may be
overridden using the normal access modifiers syntax.
Idomatic usage suggests structs should not modify their accessmodifiers for visibility and
should not declare any methods (If this is deemed necessary you should use a class instead).
They should only be used as publicly accessible value containers.
The syntax/grammar for declaring structures is similar to that of classes
(barring the struct keyword and lack of the inherits clause)
struct <StructureName> [is <AccessModifiers>] [has <Attributes>] [where <GenericParam> must be <GenericConstraints>] [implements <InterfaceName> [, <InterfaceName>]...] [<DocString>] [ [<Variables>] [<Constants>] [<Properties>] [<Methods> [<Enums>] [<Sigs>] [<Invariants>] [<Tests>] [<SharedClause>] ]... # empty (placeholder) structure struct <StructureName> [is <AccessModifiers>] [has <Attributes>] [where <GenericParam> must be <GenericConstraints>] [implements <InterfaceName> [, <InterfaceName>]...] [<DocString>] pass
in .Net, all structs inherit directly from System.ValueType, which inherits from System.Object.
# a simple Point-like struct struct CoOrds var x as int var y as int cue init(p1 as int, p2 as int) .x = p1 .y = p2 #// Declare and initialize struct objects. class TestCoOrds def main is shared # Initialize: coords1 = CoOrds() coords2 = CoOrds(10, 10) # Display results: print 'CoOrds 1: ' stop print 'x = [coords1.x], y = [coords1.y]' print 'CoOrds 2: ' stop print 'x = [coords2.x], y = [coords2.y]' assert coords1.x == 0 and coords1.y == 0 assert coords2.x == 10 and coords2.y == 10 /# Output: CoOrds 1: x = 0, y = 0 CoOrds 2: x = 10, y = 10 #/