CodeBlanks Logo Icon CodeBlanks

Defining with fn

Define functions with the fn keyword.

Defining functions

Functions are defined with fn; names are written in snake_case. Definition order doesn't matter; a function defined after main can be called inside main.

fn main() {
    selam_ver();
}

fn selam_ver() {
    println!("Merhaba!");
}

Functions that return no value actually return () (unit).

Why functions?

A function binds a repeated job to a name: the code is written once, called from many places and fixed in one place. A good function does one job and its name says so (kdv_ekle, gecerli_mi). Rust has no default parameters or overloading; different behaviors get different names.

Practice Frame

Let fn cizgi() print "----------". In main, call cizgi(), then println!("Rapor");, then cizgi() again.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn cizgi() {
    println!("----------");
}

fn main() {
    cizgi();
    println!("Rapor");
    cizgi();
}

Expected output

----------
Rapor
----------

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In which style are function names written in Rust?

  • SCREAMING_CASE
  • snake_case Correct answer
  • camelCase
  • PascalCase

Explanation: Functions and variables use snake_case, types PascalCase, constants SCREAMING_SNAKE_CASE; the compiler warns about names that break this.

2 Function keyword

Question
____ cizgi() {
    println!("----------");
}
Answer
fn cizgi() {
    println!("----------");
}

Explanation: The fn keyword defines a new function.

3 Name and style

Term Meaning
hesapla_toplam Function (snake_case)
HesapMakinesi Type (PascalCase)
MAKS_DEGER Constant
() Return of a function returning nothing

All lessons in Beginner