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);
}
```
  • Returning a refe... Chris Katko via Digitalmars-d-learn
    • Re: Returni... IchorDev via Digitalmars-d-learn
    • Re: Returni... Paul Backus via Digitalmars-d-learn
    • Re: Returni... Jacob Shtokolov via Digitalmars-d-learn
      • Re: Ret... kdevel via Digitalmars-d-learn
        • Re:... Bastiaan Veelo via Digitalmars-d-learn
          • ... kdevel via Digitalmars-d-learn
            • ... Dennis via Digitalmars-d-learn
              • ... kdevel via Digitalmars-d-learn
                • ... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
                • ... kdevel via Digitalmars-d-learn
                • ... Richard (Rikki) Andrew Cattermole via Digitalmars-d-learn
                • ... kdevel via Digitalmars-d-learn
                • ... Dennis via Digitalmars-d-learn

Reply via email to