www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - how to copy const struct with indirections to mutable one (of the

reply drug <drug2004 bk.ru> writes:
I had the following code:
```
import std.algorithm: equal;

struct Data
{
	int[3] arr;
}

int main()
{
	auto const_data = const(Data)([1, 2, 3]);
	assert(const_data.arr[].equal([1, 2, 3]));
		
	Data mutable_data = const_data;
	assert(mutable_data.arr[].equal([1, 2, 3]));
		
	return 0;
}
```
It workred fine. Now I replace static array by std.container.Array:
```
import std.algorithm: copy, equal;
import std.container: Array;

struct Data
{
	Array!int arr;
	
	this(R)(R r)
	{
		r.copy(arr[]);
	}

     ref Data opAssign(const(Data) other)
     {
         pragma(msg, __FUNCTION__);

	import std.range: lockstep;

	this.arr.length = other.arr.length;
         foreach(ref s, ref d; lockstep(other.arr[], this.arr[]))
             d = s;

         return this;
     }
}

int main()
{
	auto const_data = const(Data)([1, 2, 3]);
	assert(const_data.arr[].equal([1, 2, 3]));
		
	Data mutable_data = const_data;
	assert(mutable_data.arr[].equal([1, 2, 3]));
		
	return 0;
}
```

and it fails now because:
``
Error: conversion error from const(Data) to Data
```
I can solve my problem in other ways but I'd like to know why opAssign 
overload doesn't work in this case?

Thank in advance
Nov 29 2016
parent reply Mathias Lang <mathias.lang sociomantic.com> writes:
On Tuesday, 29 November 2016 at 10:46:04 UTC, drug wrote:
 I had the following code:
 ```
 import std.algorithm: equal;

 [...]
You are not calling the (identity) opAssign here, but postblit. To call identity opAssign, you need an already constructed instance: ``` Data mutable_data; mutable_data = const_data; ```
Nov 29 2016
parent drug <drug2004 bk.ru> writes:
29.11.2016 13:49, Mathias Lang пишет:
 On Tuesday, 29 November 2016 at 10:46:04 UTC, drug wrote:
 I had the following code:
 ```
 import std.algorithm: equal;

 [...]
You are not calling the (identity) opAssign here, but postblit. To call identity opAssign, you need an already constructed instance: ``` Data mutable_data; mutable_data = const_data; ```
Thanks for clarification!
Nov 29 2016