docs / Getting Started / Cloneable & .clone()

Cloneable & .clone()

Sometimes you want an independent deep copy up front rather than waiting for Copy-on-Write to fire. The Cloneable trait provides a .clone() method that does exactly that.

use system.io
use system.collections.list

fn main()
    let a = List([1, 2, 3])

    // .clone() forces an independent deep copy up front,
    // skipping the share-then-CoW dance.
    var b = a.clone()
    b.push(4)

    println(f"{a.length()} {b.length()}")   // 3 4

    // Strings, Maps, Arrays, and Sets are all Cloneable.
    let greeting = "hello"
    let copy = greeting.clone()
    println(copy)

All managed types (String, List, Map, Array, Set) implicitly implement Cloneable. User-defined classes get an auto-generated __clone_TypeName helper — primitives are copied bitwise, managed fields are recursively cloned. Resource types (those with fn drop(self)) intentionally do not implement Cloneable: copying a file handle or a network socket is almost always a bug.

When to reach for .clone(): when you need to keep using a managed value after passing it to a function that consumes it (see Use-After-Move below), or when you want to break aliasing eagerly to avoid a CoW copy later in a tight loop.