'scope' confusion

Andy andy.pj.hanson at gmail.com
Sun May 1 04:04:04 UTC 2022


I have another puzzle related to scoping. In this case it's about 
defining data structures that will be compatible with scope.

```
@safe @nogc pure nothrow:

extern(C) void main() {}

struct ArrayWrapper(T) {
	private T[] inner;

	ref inout(T) opIndex(immutable size_t index) inout {
		return inner[index];
	}
}

struct SomeValue {
	int* a;
}

int* f0(int[] xs) {
	return &xs[0];
}

SomeValue* f1(SomeValue[] xs) {
	return &xs[0];
}

int* g0(ArrayWrapper!int xs) {
	return &xs[0];
}

SomeValue* g1(ArrayWrapper!SomeValue xs) {
	return &xs[0];
}
```

Compiling this code results in an error in `g1` only:
```
a.d(30): Error: cannot take address of `ref return` of 
`xs.opIndex()` in `@safe` function `g1`
```


Writing `return &xs.inner[0];` would work .. which is exactly 
what `opIndex` is supposed to do. The question is how to get the 
compiler to understand this. How can I write `ArrayWrapper` so 
that it behaves the same way an array does?


More information about the Digitalmars-d mailing list