Basic Functions

  fn add(a: i32, b: i32): i32 {
    return a + b;
}

fn greet(name: []const u8) {       -- no return type = void
    debug.print("hello, {}\n", .{name});
}
  

Multiple Return Values

Violet uses anonymous structs for multiple returns:

  fn minMax(items: []const i32): struct { min: i32, max: i32 } {
    var min = items[0];
    var max = items[0];
    for item in items[1..] {
        if item.* < min { min := item.*; }
        if item.* > max { max := item.*; }
    }
    return .{ .min = min, .max = max };
}

var result = minMax(&.{3, 1, 4, 1, 5, 9});
debug.print("min={} max={}\n", .{result.min, result.max});
  

Destructure at the call site:

  var .{ min, max } = minMax(&.{3, 1, 4, 1, 5, 9});
  

The if Expression

if can produce a value with then:

  var abs = if x >= 0 then x else -x;

var label = if count = 1 then "item"
            else if count = 0 then "none"
            else "items";