Mojo trait
ImplicitlyCopyable
A marker trait to permit compiler to insert implicit calls to the copy constructor in order to make a copy of the object when needed.
Conforming a type to ImplicitlyCopyable gives the Mojo language permission
to implicitly insert a call to that types copy constructor whenever a borrowed
instance of the type is passed or assigned where an owned value is required.
Types that are expensive to copy, or where implicit copying could mask a
logic error, typically should not be ImplicitlyCopyable.
The ImplicitlyCopyable trait is a marker trait, meaning that it does not
require a type to provide any additional methods or associated aliases to
conform to this trait. However, all ImplicitlyCopyable types are required
to conform to Copyable, which ensures there is only one definition for the
logic of how a type is copied.
Note: ImplicitlyCopyable should only be used to mark structs that may
be copied implicitly. It should not be used as a trait bound
(T: ImplicitlyCopyable) on functions or types, except in special
circumstances. Generic code that may perform copies should always use the
more general T: Copyable bound. This ensures that generic code is usable
with all types that are copyable, regardless of whether they opt-in to
implicit copying.
Examples
A type can opt-in to implicit copying by conforming to ImplicitlyCopyable
(in the example below, the compiler also synthesizes a default field-wise
copy constructor, as the user didn't provide a definition):
@fieldwise_init
struct Point(ImplicitlyCopyable)
var x: Int
var y: Int
def main():
var p = Point(5, 10)
# Perform an implicit copy of `p
var p2 = pImplemented traits
AnyType,
Copyable,
ImplicitlyDestructible,
Movable
Required methods
__init__
__init__(out self: _Self, *, copy: _Self)
Create a new instance of the value by copying an existing one.
Args:
- copy (
_Self): The value to copy.
Returns:
_Self
__init__(out self: _Self, *, deinit take: _Self)
Create a new instance of the value by moving the value of another.
Args:
- take (
_Self): The value to move.
Returns:
_Self
Provided methods
copy
copy(self: _Self) -> _Self
Explicitly construct a copy of self, a convenience method for Self(copy=self) when the type is inconvenient to write out.
Returns:
_Self: A copy of this value.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!