Memory without malloc and free · 11 min · free lesson

Struct Copies: Copy and Clone

Rust copies a struct implicitly only when it is plain data marked Copy; anything that owns a resource moves, and a deep copy is an explicit .clone().

Core idea

Copy permits implicit bitwise duplication for types that own no resources; Clone is an explicit duplication whose cost depends on the type.

C and Rust, side by side

C Struct assignment copies the pointer, so b and a share one buffer, and freeing both is a double free.
#include <stdio.h>
#include <stdlib.h>

struct point { int x, y; };                  /* plain data: copying is fine */
struct path { struct point *pts; size_t len; };

int main(void) {
    struct point p = {1, 2};
    struct point q = p;                       /* an independent copy */
    q.x = 10;
    struct path a = {malloc(2 * sizeof(struct point)), 2};
    a.pts[0] = p;
    a.pts[1] = q;
    struct path b = a;                        /* copies the pointer, not the points */
    b.pts[0].x = 99;                          /* so this also changes a.pts[0] */
    printf("p.x=%d q.x=%d a.pts[0].x=%d\n", p.x, q.x, a.pts[0].x);
    free(a.pts);
    free(b.pts);                              /* ASan: attempting double-free */
    return 0;
}
Rust Point is Copy, so p survives let mut q = p; Path owns a Vec, so b is an explicit clone and let c = a is a move.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

#[derive(Clone, Debug)]
struct Path {
    points: Vec<Point>, // owns a heap buffer, so Path cannot be Copy
}

fn main() {
    let p = Point { x: 1, y: 2 };
    let mut q = p;                 // Copy: p is still usable
    q.x = 10;
    let a = Path { points: vec![p, q] };
    let mut b = a.clone();         // an explicit deep copy: a new buffer
    b.points[0].x = 99;
    println!("p.x={} q.x={} q.y={} a.points[0].x={}", p.x, q.x, q.y, a.points[0].x);
    let c = a;                     // a move: still one owner of one buffer
    println!("{} {}", c.points.len(), b.points[0].x);
}
What changes
CRust
Struct assignment always copies bytes, pointers included.Only Copy types copy implicitly; other types move to a single owner.
A shallow copy of a struct with a pointer creates two owners.A type that owns a Vec or String cannot be Copy (E0204).
A deep copy is a hand-written function..clone() is the explicit deep copy, visible at every call site.

Understand it

C struct assignment always copies bytes. For struct point that is exactly right. For struct path, which holds a pointer, b = a copies the pointer and not the points: the two structs share one buffer, a write through b changes a, and freeing both is a double free, which AddressSanitizer reports.

Rust splits this in two. A type can be Copy only if all of its fields are Copy, which means it owns nothing: integers, char, bool, shared references, and structs or tuples made of those. Assignment and by-value calls then duplicate the bytes and the source stays usable, exactly like C's struct point. #[derive(Clone, Copy)] opts a type in.

A type with a Vec, String or Box field cannot be Copy; deriving it is error E0204. Assigning such a value moves it: still a bitwise copy of the handle, but the source becomes unusable, so one buffer keeps one owner. When you really want a second, independent buffer, call .clone(). The cost is visible at the call site, the opposite of a C struct assignment that may quietly make a shallow copy.

Clone is a trait you derive or implement. For Vec<Point> it allocates and copies every element; for Rc<T> it only increments a count. Reading .clone() tells you that a duplication happens, and the type tells you its price.

The C habit, written in Rust

This is how the C version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

#[derive(Clone, Copy, Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

#[derive(Clone, Copy)]
struct Path {
    points: Vec<Point>,
}

fn main() {
    let a = Path { points: vec![Point { x: 1, y: 2 }] };
    let b = a;
    println!("{} {}", a.points.len(), b.points[0].y);
}

Practise this code in Playground ↗

Try it

Port the commented C functions: translated returns a new Path with every point moved by dx and dy and leaves the input unchanged; first_point returns a copy of the first point, or None.

What success looks like: translated returns new points while the original Path is unchanged, and first_point returns Some(Point), or None for an empty path.

Check your understanding

Why can Point { x: i32, y: i32 } derive Copy while Path { points: Vec<Point> } cannot?

Reveal the answer
  1. Copy is limited to structs with at most two fields
  2. Vec<Point> is too large to copy
  3. A bitwise copy of a Vec would make two owners of one heap buffer, so Vec is not Copy
  4. Path would need #[repr(C)] first

Copy requires every field to be Copy. Vec owns heap memory, so Path gets Clone for explicit deep copies and moves otherwise.

Go deeper

Common misconception: “Moving a value copies all of its data, so moves are expensive.”

A move copies only the value's own bytes, such as a Vec's pointer, length and capacity, and then forbids using the source. The heap data stays where it is. Only .clone() duplicates what the value owns.

  1. Classify each field: Integers and plain structs are Copy; any Vec, String, Box or file handle makes the type move-only.
  2. Choose per type: Derive Copy for plain data you would pass by value in C; derive only Clone for types that own resources.
  3. Audit the clones: Each .clone() is an explicit duplication; confirm it is needed, or borrow instead.

Transfer challenge: Add a name: String field to Point and follow the compiler errors: which derive fails, and where do you now need .clone()?

Connections

  • Dangling Pointers and Lifetimes: The compiler checks what the comment promised
  • Structs and Methods: The receiver states the pointer contract
Side-by-side comparison: the C version on the left, the Rust version on the right, then 3 rows naming what changes.
Struct Copies: Copy and Clone: the same task in C and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Struct Copies: Copy and Clone (courseId "rust-for-c-developers", lessonId "c-struct-copy-to-copy-clone")
Link: https://crabrix.com/learn/rust-for-c-developers/c-struct-copy-to-copy-clone/
Goal: Copy permits implicit bitwise duplication for types that own no resources; Clone is an explicit duplication whose cost depends on the type.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-c-developers/c-struct-copy-to-copy-clone) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.