copy

An explicit Copy trait for MoonBit values

copy
trait
moonbit
moon add totto2727/copy@0.2.0
Download zip
Author
Version
0.2.0
License
MIT
Last updated
14 days ago
Downloads
263
README

#totto2727/copy

An explicit copy trait for MoonBit values.

MoonBit does not move values when they are passed to a function, so this package is not a marker for Rust-style move semantics. Copy::copy instead creates an independent logical copy. Composite implementations recursively copy their contents, while immutable storage may be shared when it cannot expose mutation.

Copy has no blanket or default implementation. Every custom type must explicitly define how its independent logical copy is constructed so mutable fields and collections cannot be shared accidentally.

#Generic copying

Use a Copy bound when an operation must produce a logically independent value:

fn[T : Copy] duplicate(value : T) -> (T, T) {
(Copy::copy(value), Copy::copy(value))
}

test {
debug_inspect(duplicate(42), content="(42, 42)")
}

The package implements Copy for primitive and immutable scalar values, Option, Result, Array, FixedArray, ReadOnlyArray, Map, and two- and three-element tuples. Composite implementations require their contained values to implement Copy; map keys must also implement Hash and Eq.

#Custom mutable values

Mutable types define their own copy policy:

struct Counter {
mut value : Int
}

impl Copy for Counter with fn copy(self) {
Counter::{ value: self.value }
}

test {
let source = Counter::{ value: 1 }
let copied = Copy::copy(source)
copied.value = 2
debug_inspect((source.value, copied.value), content="(1, 2)")
}

MoonBit's trait syntax and generic trait bounds are documented in the official Method and Trait reference.

#
Copy

pub(open) trait Copy {
fn copy(Self) -> Self
}

Describes values that can produce an independent logical copy.

Implementations for composite values recursively copy their contents. An implementation may share immutable internal storage when doing so cannot expose mutation through the returned value.
impl Copy for Unit
impl Copy for Bool
impl Copy for Byte
impl Copy for Char
impl Copy for Int
impl Copy for Int16
impl Copy for Int64
impl Copy for UInt
impl Copy for UInt16
impl Copy for UInt64
impl Copy for Float
impl Copy for Double
impl Copy for String
impl Copy for Option[T]
impl Copy for Result[Value, CopyError]
impl Copy for FixedArray[T]
impl Copy for ReadOnlyArray[T]
impl Copy for Bytes
impl Copy for Array[T]
impl Copy for Map[Key, Value]
impl Copy for Tuple2[First, Second]
impl Copy for Tuple3[First, Second, Third]

Source Files

Powered by MoonBit

Site sourceReport issuePackagesBuild queueSkillsStatistics

© 2026 mooncakes.io