El método __copyinit__
Defina cómo se copia su tipo.
El método __copyinit__ es una lección gratuita de Mojo Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Mojo Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Mojo Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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. 🎯
Preguntas frecuentes
¿La lección «El método __copyinit__» es gratis?
Sí — el texto completo de «El método __copyinit__» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Mojo Academy, actualiza a CoddyKit PRO. El curso de Mojo Academy incluye 4 lecciones en total.
¿Qué aprenderé en «El método __copyinit__»?
Defina cómo se copia su tipo. Practicas Mojo Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Mojo Academy?
No se requiere experiencia previa. Mojo Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «El método __copyinit__»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Mojo Academy?
Sí. Cada lección de Mojo Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Semántica de copia frente a movimiento
- El método __copyinit__
- El método __moveinit__
- Destrucción y __del__