// DOCS NAVIGATION
Funções_
SOURCE: content/docs/reference/02-fundamentos.md — 02 Fundamentos / 7. Funções / Functions
Declaração Básica / Basic Declaration
PT-BR:
Funções são declaradas com func. Parâmetros requerem anotação de tipo. O tipo de retorno é indicado após returns. Se omitido, a função retorna unit (vazio).
EN-US:
Functions are declared with func. Parameters require type annotations. The return type is indicated after returns. If omitted, the function returns unit (void).
module funcoes
// Função sem parâmetros e sem retorno / Function with no parameters and no return
func saudacao() {
println("Olá!")
}
// Função com parâmetros / Function with parameters
func soma(a: int, b: int) returns int {
return a + b
}
// Parâmetros de diferentes tipos / Parameters of different types
func formatar(nome: string, idade: int) returns string {
return f"{nome} tem {idade} anos"
}
// Função booleana / Boolean function
func eh_par(n: int) returns bool {
return n % 2 == 0
}
Retorno Implícito / Implicit Return
PT-BR:
A última expressão de uma função é retornada automaticamente sem a palavra-chave return. Isso é chamado de retorno implícito.
EN-US:
The last expression of a function is automatically returned without the return keyword. This is called implicit return.
// Retorno explícito / Explicit return
func dobrar_explicito(x: int) returns int {
return x * 2
}
// Retorno implícito / Implicit return
func dobrar_implicito(x: int) returns int {
x * 2 // Sem ponto e vírgula = expressão de retorno / No semicolon = return expression
}
// Retorno implícito com bloco / Implicit return with block
func maximo(a: int, b: int) returns int {
if a > b {
a // Retorna a / Returns a
} else {
b // Retorna b / Returns b
}
}
Regra importante / Important rule: A superfície canônica não usa
;para terminar declarações ou instruções. A expressão final da função termina pela quebra de linha,}, ou fim do arquivo.
Retorno Antecipado / Early Return
PT-BR:
Use return para sair da função antes do fim, retornando um valor ou unit.
EN-US:
Use return to exit the function early, returning a value or unit.
func dividir(a: int, b: int) returns int {
if b == 0 {
return 0
// Retorno antecipado / Early return
}
return a / b
}
func validar(nome: string) {
if nome == "" {
return
// Retorno antecipado sem valor / Early return without value
}
println(f"Nome válido: {nome}")
}
Visibilidade de Funções / Function Visibility
PT-BR:
Funções são privadas por padrão (acessíveis apenas dentro do módulo). Use public para torná-las públicas.
EN-US:
Functions are private by default (accessible only within the module). Use public to make them public.
module meu.modulo
// Pública: acessível de outros módulos / Public: accessible from other modules
public func calcular_area(largura: int, altura: int) returns int {
return largura * altura
}
// Privada: apenas neste módulo / Private: only in this module
func helper_interno() returns int {
return 42
}
Funções como Valores / Functions as Values
PT-BR:
Funções podem ser passadas como argumentos usando o tipo func(T) returns R.
EN-US:
Functions can be passed as arguments using the func(T) returns R type.
func aplicar(x: int, f: func(int) returns int) returns int {
return f(x)
}
func dobrar(x: int) returns int {
return x * 2
}
func triplicar(x: int) returns int {
return x * 3
}
public func main() {
let r1 = aplicar(5, dobrar)
// 10
let r2 = aplicar(5, triplicar)
// 15
// Com closure inline / With inline closure
let r3 = aplicar(5, |x: int| x * x)
// 25
}
Funções Genéricas / Generic Functions
PT-BR:
Funções podem aceitar parâmetros de tipo genéricos com <T>. Bounds de trait (restrições) são especificados com :.
EN-US:
Functions can accept generic type parameters with <T>. Trait bounds (constraints) are specified with :.
// Função genérica simples / Simple generic function
func identidade<T>(valor: T) returns T {
return valor
}
// Com trait bound / With trait bound
func processar<T: Processavel>(item: T) returns T {
return item.processar()
}
public func main() {
let n = identidade(42)
// int
let s = identidade("hello")
// string
}
Chamadas de Função / Function Calls
// Chamada simples / Simple call
let resultado = soma(3, 4)
// 7
// Chamada aninhada / Nested call
let r = soma(dobrar(2), triplicar(3))
// soma(4, 9) = 13
// Chamada com resultado em expressão / Call in expression
let area = calcular_area(10, 20) * 2
// 400
Próximo / Next: 03 — Tipos Compostos / Composite Types
Anterior / Previous: 01 — Introdução / Introduction