Mojo trait
ImplicitlyCopyable
A marker trait to permit compiler to insert implicit calls to __copyinit__ 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 ImplicityCopyable
(in the example below, the compiler also synthesizes a default field-wise
__copyinit__() implementation, as the user didn't provide a definition):
@fieldwise_init
struct Point(ImplicitlyCopyable)
var x: Int
var y: Int
fn main():
var p = Point(5, 10)
# Perform an implicit copy of `p
var p2 = pImplemented traits
AnyType,
Copyable,
UnknownDestructibility
Aliases
__copyinit__is_trivial
alias __copyinit__is_trivial
A flag (often compiler generated) to indicate whether the implementation of __copyinit__ is trivial.
The implementation of __copyinit__ is considered to be trivial if:
- The struct has a compiler-generated trivial
__copyinit__and all its fields have a trivial__copyinit__method.
In practice, it means the value can be copied by copying the bits from one location to another without side effects.
__del__is_trivial
alias __del__is_trivial
A flag (often compiler generated) to indicate whether the implementation of __del__ is trivial.
The implementation of __del__ is considered to be trivial if:
- The struct has a compiler-generated trivial destructor and all its fields
have a trivial
__del__method.
In practice, it means that the __del__ can be considered as no-op.
Required methods
__copyinit__
__copyinit__(out self: _Self, existing: _Self, /)
Create a new instance of the value by copying an existing one.
Args:
- existing (
_Self): The value to copy.
Returns:
_Self
Provided methods
copy
copy(self: _Self) -> _Self
Explicitly construct a copy of self.
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!