Метод __copyinit__
Определяйте, как ваш тип копирует себя.
«Метод __copyinit__» — бесплатный урок Mojo Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Mojo Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Mojo Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Defining How to Copy
When a value is copied, Mojo calls a special method named __copyinit__. It builds a fresh instance from an existing one. 📋
It Runs on Assignment
Every time a copy happens, like plain assignment, __copyinit__ fires. It is the hook that defines what copying your type means.
The Method Signature
It takes the new instance to fill and a read-only existing value to copy from. You set each field on the new one.
fn __copyinit__(out self, existing: Self):
self.x = existing.xInitialize Every Field
Inside __copyinit__ your job is to give the new instance valid values for all of its fields, usually mirrored from existing.
Deep vs Shallow Copies
For heap data you decide: copy the pointer, or allocate and clone the buffer. A true deep copy gives full independence.
Why Independence Matters
A correct __copyinit__ ensures the copy owns its own data. Then editing the copy never reaches back and changes the original.
Often Derived for You
You rarely write it by hand. Marking a type Copyable lets Mojo synthesize a field-by-field __copyinit__ automatically.
@fieldwise_init
struct Point(Copyable):
var x: IntWhen to Write It Yourself
Hand-write __copyinit__ only when the default is wrong, like when you manage a raw buffer that needs cloning.
It Defines Copy Semantics
This method is literally what makes your type copyable. Without it, Mojo cannot duplicate your value on assignment.
Keep It Correct and Cheap
A good __copyinit__ is correct first and lean second. Copy only what you must so duplication stays affordable.
A Building Block of Safety
Together with moves, __copyinit__ gives Mojo its predictable value semantics. You control exactly how data is duplicated.
Quick Check
Lets check the copy initializer.
Recap
__copyinit__ defines how your type copies itself, building an independent instance. Mojo often derives it, but you can customize it. 🎯
Часто задаваемые вопросы
Урок «Метод __copyinit__» бесплатный?
Да — полный текст урока «Метод __copyinit__» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Mojo Academy, подпишись на CoddyKit PRO. Курс Mojo Academy содержит 4 уроков всего.
Чему я научусь в уроке «Метод __copyinit__»?
Определяйте, как ваш тип копирует себя. Ты практикуешь Mojo Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Mojo Academy?
Предыдущий опыт не требуется. Mojo Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Метод __copyinit__»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Mojo Academy?
Да. Каждый урок Mojo Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.