Skip to content

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.

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)
end
end

Fields are public by default.

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
end
end

Structs can implement protocols:

struct Temperature
implements Comparable[Temperature]
value: Float
def <=>(other: Temperature): Int
value <=> other.value
end
end
  • 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.

Amethyst structs compile to .NET struct types and are fully usable from C#:

struct Point
x: Float
y: Float
end

C# sees:

public struct Point {
public double X;
public double Y;
}