Setting field of struct object
Danilo
codedan at aol.com
Mon Jan 22 08:54:21 UTC 2024
On Monday, 22 January 2024 at 08:35:01 UTC, Joel wrote:
> I've lost interest in the video, looks like horrible syntax
> (F#).
Nonetheless, this usually used with Objects (new class/struct
instances), like so:
```d
import std;
struct Person {
string name, email;
ulong age;
auto withName(string name) { this.name=name; return this; }
auto withEmail(string email) { this.email=email; return this;
}
auto withAge(ulong age) { this.age=age; return this; }
}
void main() {
auto p = (new Person).withName("Tom")
.withEmail("joelcnz at gmail.com")
.withAge(44);
writeln(p);
}
```
If you convert it to a class, add an `static opCall` for
initialization,
and a toString() method, it's even nicer:
```d
module app;
import std;
class Person {
private string name, email;
private ulong age;
auto withName(string name) { this.name=name; return this; }
auto withEmail(string email) { this.email=email; return this;
}
auto withAge(ulong age) { this.age=age; return this; }
static Person opCall() => new Person();
override string toString() {
return "Person{ name: "~name~", age: "~age.to!string~",
email: "~email~" }";
}
}
void main() {
auto p = Person()
.withName("Tom")
.withEmail("joelcnz at gmail.com")
.withAge(44);
writeln(p);
}
```
It's common OOP style in some frameworks.
More information about the Digitalmars-d-learn
mailing list