On 3/23/21 4:14 PM, Imperatorn wrote:> On Tuesday, 23 March 2021 at 22:22:12 UTC, Q. Schroll wrote:
>> For a class object obj, one can use assert(obj) to get its invariants
>> checked. How to do this for structs?
>
> It's called after the constructor has run and before the destructor is
> called.
>
> It's called before entering a member function and after exiting a member
> function.
>
> So technically you could just do like obj.writeln or whatever u have 😁

Just to make sure everyone knows "it" is the invariant block:

struct S {
  int i;
  int j;

  this(int i, int j) {
    this.i = i;
    this.j = j;
  }

  invariant() {
    assert(i == 2 * j);
  }
}

void main() {
  auto s = S(1, 10);    // Won't pass the invariant check
}

Ali


Reply via email to