On Friday, 24 March 2023 at 13:53:02 UTC, bachmeier wrote:
On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov
wrote:
Is it possible to convert such records inside the structure to
the assigned type?
```d
struct MyVal
{
string value;
// Here it would be possible to use an alias to this, but
it can only be used 1 time
}
auto a = MyVal("100");
auto b = MyVal("11.2");
int MyInt = a; // Implicitly convert to target type
float myFloat = b; // Implicitly convert to target type
```
You're limited by the use of int and float. It works just fine
for structs:
```
struct MyInt {
int x;
alias x this;
this(MyString s) {
x = s.to!int;
}
void opAssign(MyString s) {
x = s.to!int;
}
}
struct MyFloat {
float x;
alias x this;
this(MyString s) {
x = s.to!float;
}
void opAssign(MyString s) {
x = s.to!float;
}
}
struct MyString {
string s;
alias s this;
}
void main() {
auto ms = MyString("100");
auto ms2 = MyString("11.2");
MyInt mi = ms;
MyFloat mf = ms2;
}
```
`opAssign` is not needed for this code to compile, but it would
be if you had
```
MyInt mi;
mi = ms;
```