それぞれを使う場面
目的に合った関数スタイルを選びます
「それぞれを使う場面」はCoddyKit上の無料Mojo Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMojo Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Mojo Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Two Tools, One Choice
Mojo gives you both def and fn. Picking well means matching the tool to what your code actually needs. 🧭
Choose def for Flexibility
Pick def when you are exploring, prototyping, or want Python-like ease without committing to types just yet.
def quick_test(data):
return len(data)Choose fn for Performance
Pick fn when speed and safety matter: tight loops, library code, and anywhere the compiler should verify your types.
fn fast_add(a: Int, b: Int) -> Int:
return a + bPrototype, Then Harden
A common path is to sketch logic with def, then rewrite the hot parts as fn once the design settles.
Type Safety Trade-off
With def you trade compile-time checks for freedom. With fn you trade freedom for early error detection.
Readability Counts Too
An fn signature reads like documentation: its types tell the next person exactly what goes in and what comes out.
fn distance(x: Float64, y: Float64) -> Float64:
return x * x + y * yMix Both Freely
You can call an fn from a def and the other way around. They live happily together in the same Mojo file.
Interop Often Wants def
When juggling dynamic Python objects through interop, a def can be smoother, since types may not be known upfront.
Hot Loops Want fn
Numeric kernels and inner loops belong in fn, where known types let Mojo generate the tightest possible code.
There Is No Wrong Start
You can always begin with whichever feels natural. Switching a def to an fn later is a small, safe edit.
A Simple Rule of Thumb
If you would benefit from the compiler checking types and squeezing out speed, write fn; otherwise def keeps things light.
Quick Check
Match the situation to the better function style.
Recap
Reach for def when you want flexibility and quick iteration, and fn when you need type safety and speed. 🎯
よくある質問
「それぞれを使う場面」レッスンは無料ですか?
はい。「それぞれを使う場面」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Mojo Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Mojo Academyコースには全4レッスンが含まれています。
「それぞれを使う場面」で何を学びますか?
目的に合った関数スタイルを選びます ブラウザで直接実行するハンズオンコードでMojo Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Mojo Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMojo Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「それぞれを使う場面」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMojo Academyレッスンでコードを書いて実行できますか?
はい。すべてのMojo Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- def関数の記述
- fn関数の記述
- それぞれを使う場面
- 戻り値の型とNone