Is there an alternative to contracts in Rust?

Before diving into Rust, I used to dabble in D (http://www.dlang.org/). One of the features that stuck with me the most were the 'contracts' that checked inputs and outputs of the functions (Contract Programming - D Programming Language):

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

Quite similar to them are the 'invariants', which verify that certain conditions within a struct are met (Contract Programming - D Programming Language):

class Date
{
    int day;
    int hour;

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

    invariant
    {
        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:

#[requires="is_diagonal(p)"]
#[ensures="is_diagonal(new_p)"]
fn double(p: Point) -> new_p: Point {
    Point {
      x: p.x + p.x,
      y: 2 * p.y
    }
}
3 Likes

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.