Fondamenti di Rust

Rust Functions and Return Values

Define functions with typed parameters and return a value without writing return.

  • Principiante
  • 2 min di lettura
  • 1 esempio eseguibile
Cosa imparerai
  • Parameters with types
  • Return type after ->
  • The last expression is returned
area(4, 5)
  1. 14, 5arguments
  2. 2width * heightthe body runs
  3. 320returned to the caller

Values go in, one value comes out

A function groups code under a name. In Rust you write the type of every parameter and, after ->, the type of the value the function returns.

The last expression of a function is its return value when it has no semicolon, so width * height is returned without the return keyword. format! builds a String the same way println! prints one.

Punti chiave

  1. Every parameter needs a type.
  2. -> u32 says what the function returns.
  3. A final expression without ; is the return value.

Esempio Rust eseguibile

Rust
Esegui il codice →
main.rs
fn area(width: u32, height: u32) -> u32 {
    width * height
}

fn describe(name: &str, size: u32) -> String {
    format!("{name} covers {size} square meters")
}

fn main() {
    let size = area(4, 5);
    println!("{}", describe("The room", size));
}
Crea un pulsante Run per questo esempio Risultato dell'esecuzione
The room covers 20 square meters

Esercitati

Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.

Hai finito questa lezione?

Segnala come imparata per tenere traccia dei tuoi progressi.

Prossima: Binary Search →

Esercitati con una sfida

Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.

Tutte le sfide