Search on Shared array and return

Jimson recdeiongmoi at gmail.com
Mon Dec 2 13:20:48 UTC 2024


Hi, could soomeone please help about how to implement the 
FindUser function or template? It should accept either a string 
or a User object as input, and if a matching user exists in the 
users collection, it should return the user object. If no match 
is found, it should return null. The Shared resource will be used 
for thread access. Also how to get User class as shared and as 
not shared ?

```d
import std.stdio;


shared User[] users;


shared class User
{
public:
     shared string username;
     shared int age;

     this(shared string username, shared int age)
     {
         this.username = username;
         this.age = age;
     }
}

shared User FindUser(string username)
{
     foreach (shared user; users)
     {
         if(user.username == username)
         {
             return user;
         }
     }

     return null;
}


void main()
{

     shared User alice = new shared User("Alice", 20);
     users ~= alice;

     shared User x;
     x = FindUser("Alice");
     if(x){
         writeln("Alice found");
     } else{
         writeln("Alice not found");
     }

}
```


More information about the Digitalmars-d-learn mailing list