www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Manually check struct invariants

reply Q. Schroll <qs.il.paperinik gmail.com> writes:
For a class object obj, one can use assert(obj) to get its 
invariants checked. How to do this for structs?
Mar 23 2021
next sibling parent reply Imperatorn <johan_forsberg_86 hotmail.com> writes:
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
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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=
er
 function.

 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
prev sibling parent reply Paul Backus <snarwin gmail.com> writes:
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_expressions
 If 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
parent Q. Schroll <qs.il.paperinik gmail.com> writes:
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:
 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_expressions
 If 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.
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.
Mar 23 2021