Valores padrão de argumentos
Torne alguns parâmetros opcionais.
Valores padrão de argumentos é uma aula grátis de Mojo Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Mojo Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Mojo Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Making a Parameter Optional
A default value lets a parameter stand in for itself. If the caller skips it, Mojo quietly uses the value you wrote in the definition.
fn greet(name: String, times: Int = 1):
for _ in range(times):
print(name)Calling With and Without
Now both calls work. Omit times and you get the default of 1; pass it and you override the default for that one call.
greet("Mojo") # times = 1
greet("Mojo", 3) # times = 3Why Defaults Are Handy
Defaults capture the common case. Most callers never touch the option, yet the power is there for the few who need it.
Defaults Go Last
Parameters with defaults must come after required ones. Otherwise Mojo could not tell which value you meant to skip.
fn open(path: String, mode: String = "r"): ... # okA Required-Then-Optional Shape
Think of it as required-first, optional-last. Reading left to right, you supply what is needed, then accept defaults for the rest. This shape is predictable.
Overriding Just One Default
To change a later default while keeping earlier ones, use a keyword. You skip straight to the option you care about.
fn make(width: Int = 80, height: Int = 24): ...
make(height=40) # width stays 80Multiple Defaults Together
A function can give several parameters defaults at once. Callers fill only what they want and let the rest fall back.
fn box(w: Int = 10, h: Int = 10, fill: String = "x"): ...Defaults Build Friendly APIs
Good defaults make a function easy to start with and powerful to grow into. Beginners call it plainly; experts tune the options.
Choosing a Sensible Default
Pick the value most callers would want anyway. A surprising default is worse than none, because it hides behavior the reader did not expect.
The Default Is Evaluated Once
The default expression belongs to the signature, not the body. Treat it as a fixed fallback that documents the normal value.
fn retry(count: Int = 3): ... # 3 is the documented normDefaults Plus Keywords Shine
Defaults and keyword calls are a great pair. Together they let you write functions with many knobs that still feel simple to call.
request(url, timeout=30, retries=5)Quick Check
Where must a parameter with a default value be placed in a Mojo function?
Recap: Smart Fallbacks
Default values make parameters optional and capture the common case. Put them last, choose them wisely, and override single ones with keywords.
Perguntas Frequentes
A aula “Valores padrão de argumentos” é grátis?
Sim — o texto completo de “Valores padrão de argumentos” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Mojo Academy, atualize para CoddyKit PRO. O curso de Mojo Academy inclui 4 aulas no total.
O que vou aprender em “Valores padrão de argumentos”?
Torne alguns parâmetros opcionais. Você pratica Mojo Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Mojo Academy?
Nenhuma experiência prévia é necessária. Mojo Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.
Quanto tempo leva a aula “Valores padrão de argumentos”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Mojo Academy?
Sim. Cada aula de Mojo Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Argumentos posicionais e nomeados
- Valores padrão de argumentos
- Retornando vários valores
- Lendo assinaturas de funções