Is there an alternative to contracts in Rust?

Before diving into Rust, I used to dabble in D ( One of the features that stuck with me the most were the ‘contracts’ that checked inputs and outputs of the functions (

int fun(ref int a, int b)
    assert(a > 0);
    assert(b >= 0, "b cannot be negative!");
out (r)
    assert(r > 0, "return must be positive");
    assert(a != 0);
    // function body

Quite similar to them are the ‘invariants’, which verify that certain conditions within a struct are met (

class Date
    int day;
    int hour;

    this(int d, int h)
        day = d;
        hour = h;

        assert(1 <= day && day <= 31);
        assert(0 <= hour && hour < 24, "hour out of bounds");

Is there an alternative to them in Rust? If not, could it make sense to implement them as an additional part of the language?

Look at Verification of Rust programs

Suggested syntax looks like this:

fn double(p: Point) -> new_p: Point {
    Point {
      x: p.x + p.x,
      y: 2 * p.y

You can get pretty far with just regular asserts. If you want syntax specifically for pre/post conditions, it looks like the contracts crate might work.

1 Like