Alias di tipo in Rust

Livello 5537 battiture

type dà un altro nome a un tipo esistente. Kilometers resta un semplice i32, quindi non aggiunge sicurezza dei tipi, ma nomi come UserMap rendono le firme più corte e chiare.

Codice Rust

// Importa HashMap per la tabella degli utenti
1use std::collections::HashMap;
2
// Kilometers è solo un altro nome per i32, non un tipo nuovo
3type Kilometers = i32;
// Dà un nome descrittivo agli ID utente
4type UserId = u64;
// Un alias può anche accorciare un tipo generico lungo
5type UserMap = HashMap<UserId, String>;
6
// Riceve Kilometers, ma accetterebbe qualsiasi i32
7fn distance_in_km(d: Kilometers) -> String {
// Crea un testo come "100 km"
8 format!("{} km", d)
9}
10
// L'alias mantiene breve questa firma
11fn get_user(users: &UserMap, id: UserId) -> Option<&String> {
// get restituisce Some(&name), o None se l'ID manca
12 users.get(&id)
13}
14
15fn main() {
16 let dist: Kilometers = 100;
// Stampa 100 km
17 println!("{}", distance_in_km(dist));
18
// Equivale a HashMap<u64, String>
19 let mut users: UserMap = HashMap::new();
20 users.insert(1, String::from("Alice"));
21 users.insert(2, String::from("Bob"));
22
// Cerca l'ID 1 e stampa solo se esiste
23 if let Some(name) = get_user(&users, 1) {
// Stampa User 1: Alice
24 println!("User 1: {}", name);
25 }
26}

Output

100 km
User 1: Alice
Esercitati a digitare questo codice

Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.

Simboli in questo codice

I simboli che digiti in questo codice Rust e quante volte compaiono.

  • :× 16
  • (× 15
  • )× 15
  • ;× 10
  • "× 10
  • ,× 8
  • {× 7
  • }× 7
  • _× 6
  • =× 6

Altri esempi Rust di livello 5

← Pratica di digitazione Rust