On Friday, 2 September 2022 at 18:35:22 UTC, Svyat wrote:
I write this code in one directory:
```
module time;
struct Time {
public int hours, minutes, seconds;
this(int h, int m, int s) {
hours = h;
minutes = m;
seconds = s;
}
Time opBinary(string op : "=")(int secos) {
assert(secos <= 86_400);
return new Time(secos / 3600, (secos % 3600) / 60,
secos % 60);
}
}
```
```
module testfortime;
import time;
import std.stdio;
void main() {
Time time = 360;
write(time.hours);
readln;
}
```
After execute 'dmd -run ./testfortime.d' i got this:
```
".\testfortime.d(6): Error: constructor `time.Time.this(int h,
int m, int s)` is not callable using argument types `(int)`
.\testfortime.d(6): too few arguments, expected `3`, got
`1`"
```
WTF? Why standart constructor isn`t callable? How it`s possible
in a programming language?
First of all, the error message is telling you what is wrong: You
are calling the constructor with only one argument, while your
constructor is declared to take 3.
If you wanted your call to work, you should have declared the
constructor as:
```
this(int h, int m = 0, int s = 0) { /* Magic */ }
```
But D will by default give you a default constructor that does
exactly that. And the constructor will be properly attributed,
because in your case, the constructor should actually be this:
```
this(int h, int m = 0, int s = 0) inout scope @safe pure nothrow
@nogc { /* Magic */ }
```
So if you just remove the constructor, things will work. Note
that in D, as soon as you define one constructor, the default one
is no longer generated.
Second, your `opBinary` cannot compile, because `Time` is a
`struct`, and if you are returning a `new Time` in `opBinary`,
you should return a `Time*`. Currently it's working because you
are not using it.
Finally, there is a module in druntime for time management, which
provides a very nice API: `core.time : Duration`. It will allow
you to do everything you want to do with your code, and more.
For example: `import core.time; auto time = 1.hour;
writeln(time);`