Re: using "invariant" with structs ... possible to call when a field value is set??

2021-08-08 Thread james.p.leblanc via Digitalmars-d-learn

On Sunday, 8 August 2021 at 11:36:51 UTC, FeepingCreature wrote:



You can make a field set function like so:

```
struct S
{
  private int x_;
  int x(int value) { return this.x_ = value; }
  int x() { return this.x_; }
}
```

This will then run invariants.

(boilerplate can automate that for you. 
https://code.dlang.org/packages/boilerplate cough 
self-advertisement cough)


FC,

Thanks! This is exactly what I had hoped might be possible!

I had made some naive "newbie-D" attempts at something like this
be couldn't get anything to work.  Thanks for providing an exable
of the exact code that would work.  Much obliged!

Best Regards,
James

PS Even more important than solving my immediate problem, I have
gained a better understanding of the struct and its member 
functions.






Re: using "invariant" with structs ... possible to call when a field value is set??

2021-08-08 Thread FeepingCreature via Digitalmars-d-learn

On Sunday, 8 August 2021 at 11:30:41 UTC, james.p.leblanc wrote:

Hello,

With structs, I understand that "invariant checking" is called 
(from dlang tour):


It's called after the constructor has run and before the 
destructor is called.

It's called before entering a member function
invariant() is called after exiting a member function.

But, is is possible to have the invariant checking be performed
whenever a field is directly set?

For example, suppose a struct "S", has a field "x".  I would 
like to

have invariance check in cases such as:

S.x = 4;

Maybe there is a hidden set field function that gets called that
might be exploitable??

Thoughts on this?  Possible?  Better paths that I should 
consider?


Best Regards,
James


You can make a field set function like so:

```
struct S
{
  private int x_;
  int x(int value) { return this.x_ = value; }
  int x() { return this.x_; }
}
```

This will then run invariants.

(boilerplate can automate that for you. 
https://code.dlang.org/packages/boilerplate cough 
self-advertisement cough)


using "invariant" with structs ... possible to call when a field value is set??

2021-08-08 Thread james.p.leblanc via Digitalmars-d-learn

Hello,

With structs, I understand that "invariant checking" is called 
(from dlang tour):


It's called after the constructor has run and before the 
destructor is called.

It's called before entering a member function
invariant() is called after exiting a member function.

But, is is possible to have the invariant checking be performed
whenever a field is directly set?

For example, suppose a struct "S", has a field "x".  I would like 
to

have invariance check in cases such as:

S.x = 4;

Maybe there is a hidden set field function that gets called that
might be exploitable??

Thoughts on this?  Possible?  Better paths that I should consider?

Best Regards,
James