Guides · 13

Operators and overloading

In Vyi, every operator is a method call. a + b calls a.@add(b), and xs[i] calls xs.@index(i). The compiler provides these methods for the number types. For a type of your own, you write the method, and the operator works on your type.

This guide shows how to give a type arithmetic, comparisons, equality, subscripts, and compound assignment, where the compiler looks for an operator method, and how tightly each operator binds.

Every operator is a method call

An operator method is a method whose name starts with @. Declare @add on a type and + works on it:

Vyi
import { println } from "@fmt"

struct Money { cents: i32 }

fn (a: Money) @add(b: Money) Money {
    return Money{ cents: a.cents + b.cents }
}

fn main() !u8 {
    con price = Money{ cents: 250 }
    con tax = Money{ cents: 20 }
    con total = price + tax
    println(total.cents)               // prints 270
    println(price.@add(tax).cents)     // prints 270
    return Ok(0)
}

price + tax and price.@add(tax) are the same call. The left operand is the receiver, and the right operand is the argument.

The argument doesn't have to be the receiver's type. The method's parameter decides what the right operand may be, exactly as it would for the written-out call. Here * multiplies an amount of money by a count:

Vyi
import { println } from "@fmt"

struct Money { cents: i32 }

fn (m: Money) @mul(count: i32) Money {
    return Money{ cents: m.cents * count }
}

fn main() !u8 {
    con ticket = Money{ cents: 1200 }
    println((ticket * 3).cents)   // prints 3600
    return Ok(0)
}

Each binary operator calls one method:

OperatorMethodOperatorMethod
+@add==@eq
-@sub!=@eq, result negated
*@mul<@lt
/@div>@lt, operands swapped
%@rem<=@le
+%@addWrap>=@le, operands swapped
-%@subWrap&@band
*%@mulWrap|@bor
<<@shl^@bxor
>>@shr

Using an operator that has no method is an error:

Vyi · does not compile
struct Money { cents: i32 }

fn main() !u8 {
    con price = Money{ cents: 250 }
    con total = price + price   // error: `+` is not implemented
    return Ok(0)
}

The message goes on to name the method that would make it work, fn (a: Money) @add(b: Money).

Comparisons

Three methods cover all six comparisons: @eq, @lt, and @le. The other three come from these. a != b is !a.@eq(b), a > b is b.@lt(a), and a >= b is b.@le(a). There is no @neq, @gt, or @ge.

So one @lt gives a type both < and >:

Vyi
import { println } from "@fmt"

struct Duration { seconds: i32 }

fn (a: Duration) @lt(b: Duration) bool {
    return a.seconds < b.seconds
}

fn main() !u8 {
    con song = Duration{ seconds: 200 }
    con ad = Duration{ seconds: 30 }
    println(ad < song)    // prints true
    println(song > ad)    // prints true
    return Ok(0)
}

Duration has no @le, so ad <= song is an error until you add one.

Unary operators

Unary minus is a method too: -a calls a.@neg(), which takes no argument:

Vyi
import { println } from "@fmt"

struct Money { cents: i32 }

fn (m: Money) @neg() Money {
    return Money{ cents: -m.cents }
}

fn main() !u8 {
    con refund = Money{ cents: 500 }
    con change = -refund
    println(change.cents)   // prints -500
    return Ok(0)
}

Three operators are not methods, and you can't give them to a type:

  • && and || evaluate their right operand only when they need it, which a method call can't do. Both operands are bool.
  • ! works only on bool.

Where the compiler finds an operator method

An operator method is found the same way as any other method (guide 04). The compiler looks first at the methods in scope where the operator is written, and then at the methods the operand's type carries with it from where it was defined. A file that imports Money can use + without naming @add, because the exported method travels with the type:

Vyi
// file: money.vyi
export struct Money { pub cents: i32 }

export fn (a: Money) @add(b: Money) Money {
    return Money{ cents: a.cents + b.cents }
}

// file: main.vyi
import { println } from "@fmt"
import { Money } from "./money"

fn main() !u8 {
    con price = Money{ cents: 250 }
    con tax = Money{ cents: 20 }
    println((price + tax).cents)   // prints 270
    return Ok(0)
}

Because scope comes first, a file that declares its own @add for Money uses that one for + in its code, and every other file keeps the original. Guide 14 covers how methods travel between files in full.

Wrapping arithmetic

On integers, +, -, and * panic with integer overflow in a debug build when the result doesn't fit the type (guide 02). When wrap-around is what you mean, write +%, -%, or *%. They wrap at the type's width in every build mode:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con top: u8 = 255
    con bottom: u8 = 0
    println(top +% 1)      // prints 0
    println(bottom -% 1)   // prints 255
    return Ok(0)
}

The wrapping operators also have compound forms: +%=, -%=, and *%=. A type of your own gets them by declaring @addWrap, @subWrap, and @mulWrap. A type with only @add has no +%.

Equality

Some types compare with == without any method from you:

  • Numbers, bool, and char compare by value.
  • Pointers compare by address. Byte views such as string literals compare by their bytes (guide 10).
  • An enum compares when every payload type in it compares. Two values are equal when they are the same variant and their payloads are equal.
  • A union value equals a value of one of its member types when it holds that member and the two are equal. Two values of the same union are equal when they hold the same member type and those members are equal.

A struct never compares on its own. Comparing every field isn't always the equality you want, so a struct gets == only from an @eq method you write. != comes with it:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn (a: Point) @eq(b: Point) bool {
    return a.x == b.x && a.y == b.y
}

fn main() !u8 {
    con start = Point{ x: 1, y: 2 }
    println(start == Point{ x: 1, y: 2 })   // prints true
    println(start != Point{ x: 0, y: 0 })   // prints true
    return Ok(0)
}

Enum equality looks inside the payload:

Vyi
import { println } from "@fmt"

enum Shape {
    Circle(i32),
    Square(i32),
}

fn main() !u8 {
    con a = Shape.Circle(2)
    println(a == Shape.Circle(2))   // prints true
    println(a == Shape.Circle(3))   // prints false
    println(a == Shape.Square(2))   // prints false
    return Ok(0)
}

A payload compares with its own ==. For a struct payload that is the struct's @eq, so the enum compares the way the struct does:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn (a: Point) @eq(b: Point) bool {
    return a.x == b.x && a.y == b.y
}

enum Location { Unknown, At(Point) }

fn main() !u8 {
    con saved = Location.At(Point{ x: 1, y: 2 })
    con current = Location.At(Point{ x: 1, y: 2 })
    println(saved == current)            // prints true
    println(saved == Location.Unknown)   // prints false
    return Ok(0)
}

Without Point's @eq, the payload has no ==, and neither does the enum. The error names the payload type:

Vyi · does not compile
struct Point { x: i32, y: i32 }

enum Location { Unknown, At(Point) }

fn main() !u8 {
    con here = Location.At(Point{ x: 1, y: 2 })
    con same = here == here  // error: operator `==` is not implemented for type Point
    return Ok(0)
}

An enum can also have an @eq of its own, which then decides what == means for it.

@eq has a companion, @hash, which no operator calls. HashMap uses both to find keys, so a type with @eq and @hash can be a map key (guide 10).

Indexing and slicing

Subscripts are methods too:

  • xs[i] calls xs.@index(i).
  • xs[i] = v calls xs.@setIndex(i, v).
  • xs[a..b] calls xs.@slice(r), where r is a Range with start set to a and end set to b. end is exclusive.

Range is a struct from @core, which every file can use without an import.

Reading by index:

Vyi
import { println } from "@fmt"

struct Readings { temps: [3]i32 }

fn (r: Readings) @index(hour: i32) i32 {
    return r.temps[hour]
}

fn main() !u8 {
    con today = Readings{ temps: [3]i32[18, 21, 19] }
    println(today[1])   // prints 21
    return Ok(0)
}

A type you can write through has @setIndex as well. It changes the value, so it takes a *mut receiver:

Vyi
import { println } from "@fmt"

struct Scoreboard { points: [3]i32 }

fn (s: Scoreboard) @index(player: i32) i32 {
    return s.points[player]
}

fn (s: *mut Scoreboard) @setIndex(player: i32, score: i32) {
    s.points[player] = score
}

fn main() !u8 {
    mut board = Scoreboard{ points: [3]i32[0, 0, 0] }
    board[1] = 10
    board[1] += 5
    println(board[1])   // prints 15
    return Ok(0)
}

board[1] = 10 calls board.@setIndex(1, 10). board[1] += 5 reads through @index and writes the sum back through @setIndex.

Slicing:

Vyi
import { println } from "@fmt"

struct Sentence { text: [*con]u8 }

fn (s: Sentence) @slice(r: Range) [*con]u8 {
    return s.text[r.start..r.end]
}

fn main() !u8 {
    con line = Sentence{ text: "hello world" }
    println(line[0..5])    // prints hello
    println(line[6..11])   // prints world
    return Ok(0)
}

A slice with no start, line[..5], starts at 0. A slice with no end, line[6..], ends at line.length(), so it needs a length() method on the type. With @index and length(), a for loop can also walk the type (guide 10).

Vec and String work the same way: @core defines their @index and @slice methods in ordinary Vyi.

Negative indexes

On a built-in array, an index the compiler can tell is negative is an error. Your own @index receives whatever the subscript says, and decides what a negative number means. This one counts back from the end:

Vyi
import { println } from "@fmt"

struct Readings { temps: [3]i32 }

fn (r: Readings) @index(hour: i32) i32 {
    if hour < 0 { return r.temps[r.temps.len + hour] }
    return r.temps[hour]
}

fn main() !u8 {
    con today = Readings{ temps: [3]i32[18, 21, 19] }
    println(today[-1])   // prints 19
    return Ok(0)
}

Vec and String panic on a negative index. A map keyed by integers could treat -1 as an ordinary key.

Compound assignment

Every arithmetic and bitwise operator has a compound form: +=, -=, *=, /=, %=, +%=, -%=, *%=, &=, |=, ^=, <<=, and >>=.

total += x stores total + x back into total. So a type with @add gets += with no extra method:

Vyi
import { println } from "@fmt"

struct Money { cents: i32 }

fn (a: Money) @add(b: Money) Money {
    return Money{ cents: a.cents + b.cents }
}

fn main() !u8 {
    mut total = Money{ cents: 0 }
    total += Money{ cents: 250 }
    total += Money{ cents: 20 }
    println(total.cents)   // prints 270
    return Ok(0)
}

The place on the left is evaluated once. A place that contains a function call would have to run the call twice, once to read and once to write, so the compiler rejects it:

Vyi · does not compile
fn nextSlot() i32 { return 0 }

fn main() !u8 {
    mut counts = [2]i32[0, 0]
    counts[nextSlot()] += 1  // error: evaluate this place twice
    return Ok(0)
}

Bind the index first: con slot = nextSlot(), then counts[slot] += 1.

Changing a value in place

Storing a whole new value isn't always what you want. A compound operator can have its own method, which changes the value in place. When that method exists, the compound operator calls it and doesn't use the plain operator at all:

CompoundMethodCompoundMethod
+=@compAdd&=@compBand
-=@compSub|=@compBor
*=@compMul^=@compBxor
/=@compDiv<<=@compShl
%=@compMod>>=@compShr
+%=@compAddWrap-%=@compSubWrap
*%=@compMulWrap

The method for %= is named @compMod, while % itself calls @rem.

A compound method takes a *mut receiver, changes the value through it, and returns nothing:

Vyi
import { println } from "@fmt"

struct Tally { votes: i32 }

fn (t: *mut Tally) @compAdd(count: i32) {
    t.votes += count
}

fn main() !u8 {
    mut tally = Tally{ votes: 0 }
    tally += 3
    tally += 2
    println(tally.votes)   // prints 5
    return Ok(0)
}

tally += 3 is the call tally.@compAdd(3), and 3 is checked against the method's count: i32 parameter. Tally has no @add, so tally + 3 is an error. A type can have either method, or both.

Precedence

From loosest to tightest:

LevelOperators
1.. ... (ranges)
2||
3&&
4|
5^
6&
7== !=
8< > <= >=
9<< >>
10+ - +% -%
11* / % *%
12prefix - ! * (dereference) & (address of)
13.field, [index], (call)

Operators of the same level group from the left, so 10 - 2 - 3 is (10 - 2) - 3:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    println(2 + 3 * 4)     // prints 14
    println((2 + 3) * 4)   // prints 20
    println(10 - 2 - 3)    // prints 5
    return Ok(0)
}

The bitwise operators &, ^, and | follow C's order, which surprises most people: they bind more loosely than ==. So flags & 4 == 4 means flags & (4 == 4), which is an error:

Vyi · does not compile
fn main() !u8 {
    con flags = 6
    if flags & 4 == 4 {   // error: this operand of `&` has type bool, where i32 is expected
        return Ok(1)
    }
    return Ok(0)
}

Put the bitwise part in parentheses:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con flags = 6
    println((flags & 4) == 4)   // prints true
    return Ok(0)
}

The operators reference has the full rules, including what the built-in operators do with negative numbers, division by zero, and shifts.