Structs
Structs are value types — they are copied on assignment and stored on the stack.
They map directly to .NET struct and are intended for small, simple data
containers.
Definition
Section titled “Definition”Fields are declared directly in the struct body with a name and type. Methods are
defined with def:
struct Point x: Float y: Float
def distance_to(other: Point): Float Math.sqrt((x - other.x) ** 2 + (y - other.y) ** 2) endendFields are public by default.
Construction
Section titled “Construction”A constructor is auto-generated from the declared fields in order. Both positional and keyword forms are accepted:
p = Point.new(1.0, 2.0)p = Point.new(x: 1.0, y: 2.0)A custom initialize can be provided to add validation or derived setup:
struct Percentage value: Float
def initialize(value: Float) raise ArgumentException, "out of range" if value < 0.0 || value > 100.0 @value = value endendProtocols
Section titled “Protocols”Structs can implement protocols:
struct Temperature implements Comparable[Temperature]
value: Float
def <=>(other: Temperature): Int value <=> other.value endendRestrictions
Section titled “Restrictions”- Structs cannot inherit from other structs or classes.
- Structs cannot be used as a base type.
- Mixins cannot be included in structs.
- Structs cannot be
abstract.
.NET Interop
Section titled “.NET Interop”Amethyst structs compile to .NET struct types and are fully usable from C#:
struct Point x: Float y: FloatendC# sees:
public struct Point { public double X; public double Y;}