digitalmars.D.learn - Manually check struct invariants
- Q. Schroll (2/2) Mar 23 2021 For a class object obj, one can use assert(obj) to get its
- Imperatorn (7/9) Mar 23 2021 It's called after the constructor has run and before the
- =?UTF-8?Q?Ali_=c3=87ehreli?= (20/27) Mar 23 2021 er
- Paul Backus (3/8) Mar 23 2021 So, you would write `assert(&obj)` for a struct instance.
- Q. Schroll (6/14) Mar 23 2021 I searched for it, but while for some reason, my brain read "If
For a class object obj, one can use assert(obj) to get its invariants checked. How to do this for structs?
Mar 23 2021
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 😁
Mar 23 2021
On 3/23/21 4:14 PM, Imperatorn wrote:> On Tuesday, 23 March 2021 at=20 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 memb=erfunction. So technically you could just do like obj.writeln or whatever u have =F0==9F=98=81 Just to make sure everyone knows "it" is the invariant block: struct S { int i; int j; this(int i, int j) { this.i =3D i; this.j =3D j; } invariant() { assert(i =3D=3D 2 * j); } } void main() { auto s =3D S(1, 10); // Won't pass the invariant check } Ali
Mar 23 2021
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?https://dlang.org/spec/expression.html#assert_expressionsIf the first AssignExpression is a pointer to a struct instance for which a Struct Invariant exists, the Struct Invariant must hold.So, you would write `assert(&obj)` for a struct instance.
Mar 23 2021
On Tuesday, 23 March 2021 at 23:27:54 UTC, Paul Backus wrote:On Tuesday, 23 March 2021 at 22:22:12 UTC, Q. Schroll wrote:I searched for it, but while for some reason, my brain read "If the first AssignExpression is a reference to a class instance for which a Class Invariant exists, the Class Invariant must hold." it failed to do so for the next sentence. Thank you.For a class object obj, one can use assert(obj) to get its invariants checked. How to do this for structs?https://dlang.org/spec/expression.html#assert_expressionsIf the first AssignExpression is a pointer to a struct instance for which a Struct Invariant exists, the Struct Invariant must hold.So, you would write `assert(&obj)` for a struct instance.
Mar 23 2021