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 fn(self) -> Self
method:
struct Foo(ExplicitlyCopyable):
var s: String
@implicit
fn __init__(out self, s: String):
self.s = s
fn copy(self) -> Self:
print("explicitly copying value")
return Foo(self.s)
struct Foo(ExplicitlyCopyable):
var s: String
@implicit
fn __init__(out self, s: String):
self.s = s
fn copy(self) -> Self:
print("explicitly copying value")
return Foo(self.s)
You can now copy objects inside a generic function:
fn copy_return[T: ExplicitlyCopyable](foo: T) -> T:
var copy = foo.copy()
return copy
var foo = Foo("test")
var res = copy_return(foo)
fn copy_return[T: ExplicitlyCopyable](foo: T) -> T:
var copy = foo.copy()
return copy
var foo = Foo("test")
var res = copy_return(foo)
explicitly copying value
explicitly copying value
Implemented traits
AnyType
,
UnknownDestructibility
Methods
copy
copy(self: _Self) -> _Self
Explicitly construct a copy of self.
Returns:
A copy of this value.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!