Definição de funções
Parâmetros e retornos
Definição de funções é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 1 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 Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Declaring a Function
You define a function with the fn keyword, a name, parentheses, and a body in curly braces.
Rust uses snake_case for function names by convention.
fn main() {
greet();
}
fn greet() {
println!("Hello from a function!");
}The main Function
Every executable Rust program starts at fn main(). It is the entry point the runtime calls first.
fn main() {
println!("Program starts here");
}Parameters
Functions can take parameters. Each parameter must declare its type after a colon.
fn main() {
print_number(7);
}
fn print_number(x: i32) {
println!("The number is {}", x);
}Multiple Parameters
Separate multiple parameters with commas. Each needs its own type annotation.
fn main() {
describe("Rust", 2010);
}
fn describe(name: &str, year: i32) {
println!("{} was released in {}", name, year);
}Return Values
Declare a return type after an arrow ->. The function gives back a value of that type.
The last expression (with no semicolon) becomes the return value.
fn main() {
let result = square(5);
println!("square is {}", result);
}
fn square(n: i32) -> i32 {
n * n
}The return Keyword
You can also return early with the return keyword. This is useful for guard conditions.
fn main() {
println!("{}", abs_value(-8));
}
fn abs_value(n: i32) -> i32 {
if n < 0 {
return -n;
}
n
}Combining Parameters and Returns
A function commonly takes inputs and produces an output. Here we add two numbers.
fn main() {
let total = add(3, 4);
println!("total {}", total);
}
fn add(a: i32, b: i32) -> i32 {
a + b
}Functions Calling Functions
Functions can call other functions, letting you build larger behavior from small reusable pieces.
fn main() {
println!("{}", double_then_add(5));
}
fn double(n: i32) -> i32 { n * 2 }
fn double_then_add(n: i32) -> i32 {
double(n) + 1
}Returning Other Types
Functions can return any type: strings, booleans, tuples, and more.
fn main() {
let (sum, product) = compute(3, 4);
println!("sum {} product {}", sum, product);
}
fn compute(a: i32, b: i32) -> (i32, i32) {
(a + b, a * b)
}Functions With No Return
A function without an arrow returns the unit type (). It does its work through side effects like printing.
fn main() {
log_message("saving file");
}
fn log_message(msg: &str) {
println!("[LOG] {}", msg);
}Order Does Not Matter
Unlike some languages, in Rust you can call a function defined later in the file. The compiler sees all functions before running.
fn main() {
println!("{}", helper());
}
fn helper() -> i32 {
99
}Quick Check
Recall how Rust functions return values.
Recap
Functions in Rust:
- Defined with
fn name(params) -> ReturnType { ... }. - Parameters need explicit types.
- The last expression (no semicolon) is the return value, or use
returnearly. - No return type means it returns
().
fn main() {
let area = rectangle_area(4, 6);
println!("area {}", area);
}
fn rectangle_area(w: i32, h: i32) -> i32 {
w * h
}Perguntas Frequentes
A aula “Definição de funções” é grátis?
Sim — o texto completo de “Definição de funções” é 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 Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.
O que vou aprender em “Definição de funções”?
Parâmetros e retornos Você pratica Learn Rust Coding 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 Learn Rust Coding?
Nenhuma experiência prévia é necessária. Learn Rust Coding 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 1 de 4.
Quanto tempo leva a aula “Definição de funções”?
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 Learn Rust Coding?
Sim. Cada aula de Learn Rust Coding 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
- Definição de funções
- Expressões e instruções
- Closures
- Fn, FnMut, FnOnce