Mojo trait
ExplicitlyCopyable
The ExplicitlyCopyable trait denotes a type whose value can be copied explicitly.
Unlike Copyable
, which denotes types that are implicitly copyable, an
explicitly copyable type can only be copied when the explicit copy
initializer is called intentionally by the programmer.
An explicit copy initializer is just a normal __init__
method that takes
a read-only
argument of Self
.
Example implementing the ExplicitlyCopyable
trait on Foo
which requires
the __init__(.., Self)
method:
struct Foo(ExplicitlyCopyable):
var s: String
@implicit
fn __init__(out self, s: String):
self.s = s
@implicit
fn __init__(out self, copy: Self):
print("explicitly copying value")
self.s = copy.s
struct Foo(ExplicitlyCopyable):
var s: String
@implicit
fn __init__(out self, s: String):
self.s = s
@implicit
fn __init__(out self, copy: Self):
print("explicitly copying value")
self.s = copy.s
You can now copy objects inside a generic function:
fn copy_return[T: ExplicitlyCopyable](foo: T) -> T:
var copy = T(foo)
return copy
var foo = Foo("test")
var res = copy_return(foo)
fn copy_return[T: ExplicitlyCopyable](foo: T) -> T:
var copy = T(foo)
return copy
var foo = Foo("test")
var res = copy_return(foo)
explicitly copying value
explicitly copying value
Implemented traits
AnyType
,
UnknownDestructibility
Methods
__init__
__init__(out self: _Self, *, other: _Self)
Explicitly construct a deep copy of the provided value.
Args:
- other (
_Self
): The value to copy.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!