December 02

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 ?

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");
    }

}
December 02
On 12/2/24 5:20 AM, Jimson wrote:

> shared User FindUser(string username)

That 'shared' makes the FindUser function shared. (More accurately, makes it so that FindUser will be executed on a 'shared' object.) However, FindUser is not a member function.

By apologizing unnecessarily for D's occasional syntax weirdness :) the fix is the following:

shared(User) FindUser(string username)

Always try to put whatever is shared, const, etc. in parenthesis.

Ali