v0.4.0
Ownership · Lesson 11.6

Custom copy

Source
Copy a move-only type on purpose with a Clone method, so that every copy is written out and runs your own code.

Between "the compiler copies each field" and "no copies at all" there is a third choice: write the copy yourself. A type with a destructor is move-only, so let b = a; is refused — but a Clone method can still make a second value on purpose, running your own code.

In real code the body does what a field-by-field copy cannot — typically duplicating something the value owns, so the copy gets its own instead of sharing. A buffer that owns a block of memory, for example, would allocate a fresh block and copy the bytes into it. Here each copy of a sheet of paper is a photocopy, and remembers how many generations it is from the original.

Three kinds of type

The typelet b = a;A second valueLesson
plain datacopies each fieldthe copyCopy
marked #NoCopy, or has a destructorrefused — use movenoneNon-copyable types
move-only, with func Clone(&self) -> Trefused — use movea.Clone(), running your bodythis lesson

Writing the copy

struct Sheet {
    text: char8[..];
    generation: int32;
}

extend Sheet {
    func Clone(&self) -> Sheet {
        PrintLine("    photocopy: generation {} -> {}", self.generation, self.generation + 1);
        return Sheet { text: self.text, generation: self.generation + 1 };
    }

    func ~Sheet(&var self) {
        PrintLine("    shredding generation {}", self.generation);
    }
}

Clone is an ordinary method. self is the value being copied, borrowed read-only with &self so the copy cannot change or consume it, and the method returns the new value. Every field you want in the copy, you set yourself — leave text: self.text out of the struct literal and the compiler asks for it.

The destructor is there to show that every copy is a value of its own, with its own end. It is also what makes Sheet move-only in the first place.

Every copy is written out

A binding takes a clone:

let original = Sheet { text: "Minutes", generation: 1 };
let copy = original.Clone();

copy is generation 2. original is untouched, still generation 1. What Clone returns is a fresh value that nobody else holds, so a plain = takes it — no move needed.

Passing by value needs a sheet of its own. Show takes its sheet by value, so the caller hands over a clone, and that clone is shredded when Show returns:

func Show(sheet: Sheet) {
    PrintLine("    showing '{}', generation {}", sheet.text, sheet.generation);
}
Show(copy.Clone());
passing by value:
    photocopy: generation 2 -> 3
    showing 'Minutes', generation 3
    shredding generation 3

Because Clone is a call, every copy appears in the source where it happens. Nothing is duplicated behind your back by an assignment or a call.

Assigning over a live value

Assignment over a value that already exists does two things, in a fixed order — it makes the new value first, then ends the old value's life:

var board = Sheet { text: "Agenda", generation: 1 };
board = copy.Clone();
flowchart LR
    c["`copy`<br/>generation 2"] -- "first, `Clone` runs:<br/>a photocopy" --> n["new sheet<br/>generation 3"]
    b["`board`<br/>generation 1"] -- "then the old value ends" --> s["shredding<br/>generation 1"]
    n -- "finally the new one<br/>is installed" --> b2["`board`<br/>generation 3"]

The output shows the order: the photocopy line comes before the shredding line.

Only Clone makes a copy

A sheet made on the spot is not a copy of anything, so it moves straight in with no photocopy. That is why var board = Sheet { … }; prints nothing, and why board = Sheet { … }; would print only the shredding of the old sheet. A value handed over with move is not copied either.

WrittenRuns Clone?
let copy = original;refused — Sheet is move-only
let copy = original.Clone();yes
Show(copy.Clone())yes
board = copy.Clone();yes
var board = Sheet { … };no — made on the spot
Show(move copy)no — moved, and copy is finished

At the end of Main, three sheets are still alive — original, copy and board — and each is shredded once, newest first: generation 3, then 2, then 1.

A type whose Clone has exactly this shape can also implement the Core interface Cloneable, so that generic code bounded by T: Cloneable can copy it too.

The program

The whole lesson is one package in the Examples repository. Its comments explain every step.

Src/Main.rux
// Between "the compiler copies each field" and "no copies at all" there is a third choice: write
// the copy yourself, as a `Clone` method. A type with a destructor is move-only, so `let b = a;`
// is refused; `a.Clone()` makes the copy instead, and it runs your code. `self` is the value being
// copied, borrowed read-only so the copy cannot change or consume it, and the method returns the
// new value.
//
// Because `Clone` is an ordinary method call, every copy is written where it happens: nothing is
// duplicated behind your back by an assignment or a call. In real code the body does what a
// field-by-field copy cannot, typically duplicating something the value owns so the copy gets its
// own instead of sharing. Here each copy of a sheet is a photocopy and remembers how many
// generations it is from the original. The destructor shows that every copy is a value of its
// own, with its own end. (A type that implements `Core::Cloneable` with this method can also be
// copied by generic code bounded by `T: Cloneable`.)
import Io::PrintLine;

struct Sheet {
    text: char8[..];
    generation: int32;
}

extend Sheet {
    func Clone(&self) -> Sheet {
        PrintLine("    photocopy: generation {} -> {}", self.generation, self.generation + 1);
        return Sheet { text: self.text, generation: self.generation + 1 };
    }

    func ~Sheet(&var self) {
        PrintLine("    shredding generation {}", self.generation);
    }
}

// Taken by value, so the call needs a sheet of its own: the caller hands over a clone.
func Show(sheet: Sheet) {
    PrintLine("    showing '{}', generation {}", sheet.text, sheet.generation);
}

func Main() -> int {
    PrintLine("binding:");
    let original = Sheet { text: "Minutes", generation: 1 };
    let copy = original.Clone();
    PrintLine("    original {}, copy {}", original.generation, copy.generation);

    PrintLine("passing by value:");
    Show(copy.Clone());

    // Assigning over a live value makes the new copy first, then ends the old value's life.
    // Only `Clone` makes a photocopy. A sheet made on the spot is not a copy of anything, so it
    // moves straight in with no photocopy, here and in `board = Sheet { ... };`.
    PrintLine("assigning:");
    var board = Sheet { text: "Agenda", generation: 1 };
    board = copy.Clone();
    PrintLine("    board now holds '{}', generation {}", board.text, board.generation);

    PrintLine("end of Main:");
    return 0;
}

Run it

cd Examples/Ownership/CustomCopy
rux run
binding:
    photocopy: generation 1 -> 2
    original 1, copy 2
passing by value:
    photocopy: generation 2 -> 3
    showing 'Minutes', generation 3
    shredding generation 3
assigning:
    photocopy: generation 2 -> 3
    shredding generation 1
    board now holds 'Minutes', generation 3
end of Main:
    shredding generation 3
    shredding generation 2
    shredding generation 1

Common mistakes

Try it yourself

  1. Add let third = copy.Clone(); after the binding. Predict every photocopy and shredding line before you run it.
  2. Change Show(copy.Clone()) to Show(move copy). The photocopy line disappears — and a later line no longer compiles. Which one, and why?
  3. Change Show(copy.Clone()) to Show(copy) and read the help line. Which two fixes does it offer?

Learn more