Operator Overloading and Custom Iterators

28.1 Operator Overloading

Overloadable: + - * / % < == (with !=, >, <=, >=, and op= derived automatically). Both operands must be the same type.

No overloading of [], (), or bitwise operators (as of 0.4).

struct Vec2 {
	x f64
	y f64
}

fn (a Vec2) + (b Vec2) Vec2 { return Vec2{a.x + b.x, a.y + b.y} }
fn (a Vec2) - (b Vec2) Vec2 { return Vec2{a.x - b.x, a.y - b.y} }
fn (a Vec2) * (b Vec2) Vec2 { return Vec2{a.x * b.x, a.y * b.y} }
fn (a Vec2) == (b Vec2) bool { return a.x == b.x && a.y == b.y }
fn (a Vec2) < (b Vec2) bool { return a.x < b.x }
fn (v Vec2) str() string { return '(${v.x}, ${v.y})' }

fn main() {
	mut a := Vec2{1, 2}
	b := Vec2{3, 4}
	println(a + b)
	a += b                       // auto-derived from +
	println(a != b)              // auto-derived from ==
	println(a >= b)              // auto-derived from < and ==
}

28.2 Custom Iterators

struct Range {
mut:
	cur int
	end int
}

fn (mut r Range) next() ?int {       // any struct with `next() ?T` works in `for ... in`
	if r.cur >= r.end { return none }
	defer { r.cur++ }
	return r.cur
}

fn main() {
	for x in Range{0, 5} { println(x) }
}