Returning a reference to be manipulated

Jacob Shtokolov jacob.100205 at gmail.com
Thu Apr 13 22:09:48 UTC 2023


On Thursday, 13 April 2023 at 07:05:10 UTC, Chris Katko wrote:
> I'm trying to figure out how to return a reference to something 
> that may not be a reference type.

```d
@safe:

struct Stats
{
     float[string] data;

     ref opIndex(string key) return
     {
         // The `require()` takes care of non-existing values, 
initializing them
         return data.require(key, 0);
     }
}

void main()
{
     import std.stdio;

     Stats foo;

     // 1. You can't "capture" a reference, only use it directly
     foo["tacos"] += 2;

     // 2. You can use an alternative function-calling form 
(sometimes replaced by the `with` operator)
     ((ref float val) => val += 2)(foo["burritos"]);

     // 3. As a last resort, use pointers or make struct wrappers 
around them
     auto x = &foo["quesadillas"];
     *x += 2;

     writeln(foo);
}
```


More information about the Digitalmars-d-learn mailing list