Skip to main content

Mojo trait

Copyable

The Copyable trait denotes a type whose value can be explicitly copied.

Example implementing the Copyable trait on Foo, which requires the def __init__(out self,*, copy: Self) method:

struct Foo(Copyable):
    var s: String

    def __init__(out self, s: String):
        self.s = s

    def __init__(out self, *, copy: Self):
        print("copying value")
        self.s = copy.s

You can now copy objects inside a generic function:

def copy_return[T: Copyable](foo: T) -> T:
    var copy = foo.copy()
    return copy^

var foo = Foo("test")
var res = copy_return(foo)
copying value

Implemented traits

AnyType, 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?