www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - opIndexAssign

reply Salih Dincer <salihdb hotmail.com> writes:
Hi,

opIndexAssign, which is void, cannot compromise with opIndex, 
which is a ref!  Solution: Using opSliceAssign.  Could this be a 
bug?  Because there is no problem in older versions (e.g. 
v2.0.83).

```d
struct S
{
   int[] i;

   ref opIndex(size_t index) => i[index];

   auto opSliceAssign/*
   auto opIndexAssign//*/
   (int value) => i[] = value;
}

void main()
{
   auto s = S([1, 2]);

   s[] = 2;
   assert(s.i == [2, 2]);

   s[1] = 42;
   assert(s.i == [2, 42]);
}
```
**Source:** https://run.dlang.io/is/G3iBEw
If you converted comment line 7 with // and you will see this 
error:

 onlineapp.d(19): Error: function `onlineapp.S.opIndexAssign(int 
 value)` is not callable using argument types `(int, int)`
 onlineapp.d(19):        expected 1 argument(s), not 2
SDB 79
Oct 02 2023
parent reply Timon Gehr <timon.gehr gmx.ch> writes:
On 10/3/23 00:11, Salih Dincer wrote:
 Hi,
 
 opIndexAssign, which is void, cannot compromise with opIndex, which is a 
 ref!  Solution: Using opSliceAssign.  Could this be a bug?  Because 
 there is no problem in older versions (e.g. v2.0.83).
 
 ```d
 struct S
 {
    int[] i;
 
    ref opIndex(size_t index) => i[index];
 
    auto opSliceAssign/*
    auto opIndexAssign//*/
    (int value) => i[] = value;
 }
 
 void main()
 {
    auto s = S([1, 2]);
 
    s[] = 2;
    assert(s.i == [2, 2]);
 
    s[1] = 42;
    assert(s.i == [2, 42]);
 }
 ```
 **Source:** https://run.dlang.io/is/G3iBEw
 If you converted comment line 7 with // and you will see this error:
 
 onlineapp.d(19): Error: function `onlineapp.S.opIndexAssign(int 
 value)` is not callable using argument types `(int, int)`
 onlineapp.d(19):        expected 1 argument(s), not 2
SDB 79
void opIndexAssign(int value, int index){ i[index] = value; }
Oct 05 2023
parent Salih Dincer <salihdb hotmail.com> writes:
On Thursday, 5 October 2023 at 12:00:22 UTC, Timon Gehr wrote:
 void opIndexAssign(int value, int index){ i[index] = value; }
In this case I need to define many operator overloads. For example (+=), this won't work without returns ref: ```d s[1] += 3;  assert(s.i == [2, 45]); // Error: no `[]` operator overload for type `S` ``` SDB 79
Oct 05 2023