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 borrowed
argument of Self
.
Example implementing the ExplicitlyCopyable
trait on Foo
which requires
the __init__(.., Self)
method:
struct Foo(ExplicitlyCopyable):
var s: String
fn __init__(inout self, s: String):
self.s = s
fn __init__(inout self, copy: Self):
print("explicitly copying value")
self.s = copy.s
struct Foo(ExplicitlyCopyable):
var s: String
fn __init__(inout self, s: String):
self.s = s
fn __init__(inout 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
Methods
__init__
__init__(inout self: T, /, *, other: T)
Explicitly construct a deep copy of the provided value.
Args:
- other (
T
): The value to copy.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!
😔 What went wrong?