Associative Array, get value instead of poiter using `if (auto ..)`, possible?

ryuukk_ ryuukk.dev at gmail.com
Sat Aug 31 14:36:12 UTC 2024


On Saturday, 31 August 2024 at 14:25:29 UTC, Paul Backus wrote:
> On Saturday, 31 August 2024 at 12:47:25 UTC, ryuukk_ wrote:
>> ```D
>> void main()
>> {
>>     int[string] test;
>>
>>     test["hello"] = 42;
>>
>>     if (auto it = "hello" in test)
>>     {
>>
>>     }
>>
>> }
>> ```
>> Is there a way to get the value instead of a pointer? while 
>> keeping the conciseness (one line)
>
> Once the next release of Phobos comes out, with [PR 9039][1] 
> merged, you'll be able to do it like this:
>
> ```d
> import std.typecons;
>
> Nullable!V maybeGet(K, V)(V[K] aa, K key)
> {
>     if (auto ptr = key in aa)
>         return nullable(*ptr);
>     else
>         return Nullable!V.init;
> }
>
> void main()
> {
>     import std.stdio;
>
>     int[string] test = ["hello": 42];
>
>     if (auto it = test.maybeGet("hello"))
>     {
>         writeln("hello => ", it.get);
>     }
> }
> ```
>
> [1]: https://github.com/dlang/phobos/pull/9039

See, that's the thing i hate about D, solving simple problem 
requires templates + import + function call

I already lost interest, i'll solve that problem with something 
else


More information about the Digitalmars-d-learn mailing list