What is the move() method in D language?
Overview
The move() method in D
language copies a
source value into the target. It can also do this via a type of copy known as a destructive copy when necessary. This kind of copy occurs when source is defined with a destructor. The source is reset to its .init value after it is moved into target. Otherwise, it is left unchanged.
Note: An assertion failure will be thrown if the source value has internal pointers that point to itself and doesn’t define an
opPostMovemethod, which will give it the permission to do so. This will cause thesourcenot to be moved and trigger the earlier mentioned error.
Syntax
move(source,target)
Parameters
source: This is a struct object value whose elements will be copied into another value.target: This is the variable into which the values of thesourcewill be copied.
Return value
The move() method returns a struct object value with the value of the source object struct copied into it.
Example
void main(){import std.algorithm.mutation;import std.stdio: write, writeln, writef, writefln;// Structs without destructors are simply copiedstruct Struct_Value{int c = 1;int d = 2;}Struct_Value val1 = { 10, 11 };Struct_Value val2;move(val1, val2);writeln(val2);writeln(val1);}
Explanation
- Line 1 and 19: We start and end the main function.
- Lines 3 and 4: We import the relevant methods.
- Lines 6–12: We declare a struct named
Struct_Valueand twostructobjectsval1andval2. - Line 14: We use the
move()function to copy all the values ofval1intoval2. - Lines 16 and 17 : We display the values of source
val1and targetval2aftermove()method operation.