__copyinit__メソッド
型のコピー方法を定義します
「__copyinit__メソッド」はCoddyKit上の無料Mojo Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これは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時間対応のAIチューター)、Mojo Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Mojo Academyコースには全4レッスンが含まれています。
「__copyinit__メソッド」で何を学びますか?
型のコピー方法を定義します ブラウザで直接実行するハンズオンコードでMojo Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Mojo Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMojo Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「__copyinit__メソッド」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMojo Academyレッスンでコードを書いて実行できますか?
はい。すべてのMojo Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- コピーとムーブのセマンティクス
- __copyinit__メソッド
- __moveinit__メソッド
- 破棄と__del__