Alias di tipo in Rust

Livello 4677 battiture

Gli alias di tipo creano nomi leggibili per tipi complessi. Non creano nuovi tipi.

Codice Rust

// Importa HashMap per la mappa degli utenti
1use std::collections::HashMap;
2
// UserId è solo un altro nome per u64, non un nuovo tipo
3type UserId = u64;
// Username indica String
4type Username = String;
// Gli alias possono nominare tipi lunghi e usare altri alias
5type UserMap = HashMap<UserId, Username>;
// Un alias generico che fissa il tipo di errore a String
6type Result<T> = std::result::Result<T, String>;
7
// Si legge come il dominio: cerca uno Username per UserId
8fn get_user(users: &UserMap, id: UserId) -> Result<&Username> {
// get dà Option<&String>; ok_or trasforma None in Err("User not found")
9 users.get(&id).ok_or(String::from("User not found"))
10}
11
// Punto di ingresso del programma
12fn main() {
// UserMap è esattamente HashMap<u64, String>, quindi HashMap::new() funziona
13 let mut users: UserMap = HashMap::new();
14
// Aggiunge tre utenti con ID da 1 a 3
15 users.insert(1, String::from("Alice"));
16 users.insert(2, String::from("Bob"));
17 users.insert(3, String::from("Carol"));
18
// L'ID 2 esiste
19 match get_user(&users, 2) {
// Stampa "Found: Bob"
20 Ok(name) => println!("Found: {}", name),
// Non eseguito per l'ID 2
21 Err(e) => println!("Error: {}", e),
22 }
23
// L'ID 99 non esiste
24 match get_user(&users, 99) {
25 Ok(name) => println!("Found: {}", name),
// Stampa "Error: User not found"
26 Err(e) => println!("Error: {}", e),
27 }
28}

Output

Found: Bob
Error: User not found
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.

  • :× 25
  • (× 22
  • )× 22
  • ,× 16
  • "× 16
  • ;× 9
  • =× 9
  • >× 9
  • {× 8
  • }× 8

Altri esempi Rust di livello 4

← Pratica di digitazione Rust