Thread overview
Don't allow to reassign, but content is editable
5 days ago
tcak
5 days ago
Adam D. Ruppe
5 days ago
Kagamin
5 days ago

In javascript, with "const" keyword, you assign an object to a variable. Later, you cannot assign anything else to that variable, but content of it still can be changed. No matter by using "immutable" or "const", I cannot imitate that. Is there a way to do this without an overhead (like calling a function to create a pointer)?

Example:

class Test
{
public int[] a;

public this(){ a = new int[5]; }

@property auto b(){ return a.ptr; }  // this is a possibility, but results with overhead of calling. Also, b is not an array anymore, just int*.

}

I want this to be possible:
test.a[3] = 7;

But this wouldn't be allowed:
test.a = new int[14];

5 days ago

On Wednesday, 7 April 2021 at 12:28:25 UTC, tcak wrote:

>
@property auto b(){ return a.ptr; }  // this is a possibility, but results with overhead of calling. Also, b is not an array anymore, just int*.

Why are you returning a.ptr instead of just a?

If you return just a, it works fine for what you want.

You can virtually guarantee no calling overhead by simply making that final; then it is easy for the compiler to inline in all cases.

5 days ago
struct A
{
    private int[] a;
    this(int[] b){a=b;}
    int[] c(){ return a; }
    @disable void opAssign();
}
struct B
{
    A a;
    this(int){ a=new int[5]; }
    int[] b(){ return a.c; }
    void f(){ a=new int[5]; }
}