Copy Clone
copy_clone.nr29 lines
copy_clone.nr· neuro
// `Copy` and `Clone`: `@derive(Copy, Clone)`. A struct that derives `Copy` is duplicated on
// assignment, so the source stays valid. A struct that derives `Clone` supports an explicit
// `.clone()` deep copy. Both yield independent values.
@derive(Copy, Clone)
struct Point {
x: i32,
y: i32
}
func main() -> i32 {
val a = Point { x: 3, y: 4 }
// Copy: `a` is duplicated into `b`; `a` remains usable afterwards.
val b = a
val sum_a = a.x + a.y // 7: `a` is still valid after the copy
// Clone: an explicit independent copy via @derive(Clone).
val c = b.clone()
val sum_c = c.x + c.y // 7
println("a = ({a.x}, {a.y})")
println("b = a = ({b.x}, {b.y}) (Copy: a still usable)")
println("c = b.clone = ({c.x}, {c.y})")
println("a.x + a.y = {sum_a}")
println("c.x + c.y = {sum_c}")
return sum_a + sum_c // 7 + 7 = 14
}
neuroc run copy_clone.nr
a = (3, 4)
b = a = (3, 4) (Copy: a still usable)
c = b.clone = (3, 4)
a.x + a.y = 7
c.x + c.y = 7