Struct nested function

Ferhat Kurtulmuş aferust at gmail.com
Wed Sep 13 08:15:21 UTC 2023


On Wednesday, 13 September 2023 at 05:58:13 UTC, vino wrote:
> Hi All,
>
>   Request your help, I have a struct which has many functions, 
> I need to run a function from within another function(From 
> Display function execute the runner function), an example as 
> below
>
> From,
> Vino

The problem starts here:

```string *runnerptr = &runner;```

You are trying to assign a delegate to string*. Even if we fix 
this, we hit another error because D programming language does 
not allow capturing a reference to this, which is not permitted 
in tasks (IMHO). We fix this using a lambda ```auto result = 
task(() => runner());```. Then the final code that runs should be 
like:

```d
import std.stdio: writeln;
import std.algorithm: joiner;
import std.parallelism: task;
import std.typecons: tuple;

struct MainEngine {
     int rno;
     string firstname;
     string lastname;
     int age;

     this(in int _rno) { rno = _rno; }
     auto ref FirstName(in string _firstname) { firstname = 
_firstname; return this; }
     auto ref LastName(in string _lastname) { lastname = 
_lastname; return this; }
     auto ref Age(in int _age) { age = _age; return this; }
     auto Display () {
         auto runner(string status = "Male")
         {
             auto record = tuple([firstname,",",lastname].joiner, 
age, status);
             return record;
         }

         auto result = task(() => runner());
         //writeln(typeof(result).stringof);
         result.executeInNewThread;
         result.yieldForce;
         return result;
     }
}

void main () {
     auto mrunner = 
MainEngine(1).FirstName("Fname").LastName("Lname").Age(25).Display();
     writeln((*mrunner).yieldForce); // Access the result field to 
get the value returned by the task
}
```


More information about the Digitalmars-d-learn mailing list