Operator Overloading

Structs in Shim can create their own definitions for operators like +, -, *, and /.

struct Point {
    x,
    y,

    fn add(self, other) {
        Point(
            self.x+other.x,
            self.y+other.y,
        )
    }

    fn eq(self, other) {
        self.x == other.x and self.y == other.y
    }
}

print(Point(1, 2) + Point(3, 4))
print(Point(1, 2) == Point(3, 4))
Press the play button to execute
MethodOperator
add+
sub-
mul*
div/
modulus%
eq==
gt>
gte>=
lt<
lte<=
containsin

These calls always dispatch on the left operand. No operations are automatically defined. So if you define gt and eq you still need to define lt. If a and b are different types and you want both a + b and b + a to work you need to define add on both types.

Overloading the in Operator

Structs can overload the in operator, not just arithmetic operators. Here’s an example of using it to define a custom RangeInclusive type.

struct RangeInclusive {
    lower,
    upper,

    fn contains(self, value) {
        value.clamp(self.lower, self.upper) == value
    }
}

let bounds = RangeInclusive(0, 10)
print(-5, -5 in bounds)
print(0, 0 in bounds)
print(5, 5 in bounds)
print(10, 10 in bounds)
print(15, 15 in bounds)
Press the play button to execute

String Formatting

While Shim provides a default implementation for formatting structs as strings, structs can customize this behavior by defining a format method. This method takes self and any other arguments provided in the format specification.

struct Gauge {
    val,
    max,

    // Format gauge like: [==-----]
    fn format(self, start="[", fill="=", empty="-", end="]") {
        let out = start
        for i in 0..self.max {
            out += if i < self.val { fill } else { empty }
        }
        out + end
    }
}

let a = Gauge(val=3, max=10)
print("Repr:   ", a) // This might be changed in the future to use .format
print("Default: \(a)")
print("Round:   \(a, start="(", fill="O", end=")")")
Press the play button to execute

The .format method can take positional and keyword arguments.