Il Linguaggio di Programmazione Rust
di Steve Klabnik e Carol Nichols con contribuzioni dalla comunità di Rust; tradotto in Italiano dal Rust User Group di Verona grazie al lavoro degli studenti dell'ITIS G. Marconi
Questa versione del libro assume che tu stia utilizzando Rust 1.67.1 (rilasciato il 9 febbraio 2023) o successivo. Consulta la sezione "Installazione" del capitolo 1 per imparare a installare o aggiornare Rust.
Altre traduzioni curate dalla comunità sono disponibili nell'elenco dedicato.
Prefazione
Non è sempre stato così chiaro, ma il linguaggio di programmazione Rust è fondamentalmente circa l'empowerment: non importa che tipo di codice stai scrivendo ora, Rust ti dà il potere di andare più lontano, di programmare con fiducia in una varietà più ampia di domini che prima.
Prendi, ad esempio, il lavoro a "livello di sistema" che si occupa di dettagli di basso livello di gestione della memoria, rappresentazione dei dati e Concurrency. Tradizionalmente, questo ambito di programmazione è visto come arcano, accessibile solo a pochi eletti che hanno dedicato gli anni necessari per imparare a evitare le sue trappole infami. E anche coloro che lo praticano lo fanno con cautela, affinché il loro codice non sia aperto a exploit, crash, o corruzione.
Rust elimina queste barriere eliminando le vecchie trappole e fornendo un set di strumenti amichevole e lucidato per aiutarti lungo il percorso. I programmatori che hanno bisogno di "scendere" a un controllo di livello inferiore possono farlo con Rust, senza assumere il rischio abituale di crash o buchi di sicurezza, e senza dover imparare i punti sottili di un toolchain capriccioso. Ancora meglio, il linguaggio è progettato per guidarti naturalmente verso il codice affidabile che è efficiente in termini di velocità e uso della memoria.
I programmatori che stanno già lavorando con codice a basso livello possono usare Rust per aumentare le loro ambizioni. Ad esempio, l'introduzione del parallelismo in Rust è una operazione a basso rischio: il compilatore catturerà i classici errori per te. E puoi affrontare ottimizzazioni più aggressive nel tuo codice con la fiducia che non introdurrà accidentalmente crash o vulnerabilità.
Ma Rust non si limita alla programmazione di sistemi a basso livello. È abbastanza espressivo e ergonomico per rendere piacevole scrivere app CLI, server web e molti altri tipi di codice - troverai semplici esempi di entrambi più avanti nel libro. Lavorare con Rust ti permette di sviluppare competenze che si trasferiscono da un dominio all'altro; puoi imparare Rust scrivendo un'app web, poi applicare quelle stesse competenze per targettare il tuo Raspberry Pi.
Questo libro abbraccia pienamente il potenziale di Rust per potenziare i suoi utenti. È un testo amichevole e accessibile, pensato per aiutarti a fare un salto di livello non solo nella tua conoscenza di Rust, ma anche nel tuo reach e nella tua confidenza come programmatore in generale. Quindi immergiti, preparati a imparare - e benvenuto nella comunità Rust!
— Nicholas Matsakis e Aaron Turon
Introduzione
Nota: Questa edizione del libro è la stessa di The Rust Programming Language disponibile in formato cartaceo e ebook da No Starch Press.
Benvenuto a The Rust Programming Language, un libro introduttivo su Rust. Il linguaggio di programmazione Rust ti aiuta a scrivere software più veloce e affidabile. Gli strumenti di alto livello e il controllo di basso livello sono spesso in contrasto nella progettazione del linguaggio di programmazione; Rust sfida quel conflitto. Equilibrando una potente capacità tecnica e un'eccellente esperienza di sviluppo, Rust ti dà l'opzione di controllare dettagli di basso livello (come l'uso della memoria) senza tutto il fastidio tradizionalmente associato a tale controllo.
Per chi è Rust
Rust è ideale per molte persone per vari motivi. Diamo un'occhiata ad alcuni dei gruppi più importanti.
Team di sviluppatori
Sta risultando che Rust è uno strumento produttivo per la collaborazione tra grandi team di. sviluppatori con vari livelli di conoscenza della programmazione di sistemi. Il codice di basso livello è propenso a vari bug sottili, che nella maggior parte degli altri linguaggi possono essere catturati solo attraverso test estensivi e un'attenta revisione del codice da parte di sviluppatori esperti. In Rust, il compilatore svolge un ruolo di guardiano rifiutando di compilare codice con questi bug elusivi, inclusi i bug di Concurrency. Lavorando a fianco del compilatore, il team può dedicare il suo tempo a concentrarsi sulla logica del programma piuttosto che a caccia di bug.
Rust porta anche strumenti di sviluppo contemporanei nel mondo della programmazione dei sistemi:
- Cargo, il gestore di dipendenze e strumento di compilazione incluso, rende l'aggiunta, la compilazione e la gestione delle dipendenze indolori e coerenti in tutto l'ecosistema Rust.
- Lo strumento di formattazione Rustfmt garantisce uno stile di codifica coerente attraverso gli sviluppatori.
- Il Rust Language Server alimenta l'integrazione dell'Ambiente di Sviluppo Integrato (IDE) per il completamento del codice e i messaggi di errore inline.
Utilizzando questi e altri strumenti nell'ecosistema Rust, gli sviluppatori possono essere produttivi mentre scrivono codice di livello sistema.
Studenti
Rust è per gli studenti e per coloro che sono interessati a imparare i concetti sui sistemi . Usando Rust, molte persone hanno imparato argomenti come lo sviluppo di sistemi operativi. La community è molto accogliente e felice di rispondere alle domande degli studenti. Attraverso sforzi come questo libro, i team di Rust vogliono rendere i concetti dei sistemi più accessibili a più persone, specialmente a quelle nuove nella programmazione.
Aziende
Centinaia di aziende, grandi e piccole, usano Rust in produzione per vari compiti, tra cui strumenti da riga di comando, servizi web, strumentazione DevOps, dispositivi incorporati, analisi audio e video e transcodifica, criptovalute, bioinformatica, motori di ricerca, applicazioni Internet of Things, apprendimento automatico, e persino parti importanti del browser web Firefox.
Sviluppatori Open Source
Rust è per le persone che vogliono costruire il linguaggio di programmazione Rust, la comunità, gli strumenti per sviluppatori e le librerie. Ci piacerebbe che tu contribuissi al linguaggio Rust.
Persone che apprezzano la velocità e la stabilità
Rust è per le persone che desiderano velocità e stabilità in un linguaggio. Con velocità, intendiamo sia quanto velocemente il codice Rust può essere eseguito e la velocità con cui Rust ti consente di scrivere programmi. I controlli del compilatore Rust garantiscono stabilità attraverso aggiunta di funzionalità e rifattorizzazione. Questo è in contrasto con il codice legacy fragile in i linguaggi senza questi controlli, che gli sviluppatori spesso hanno paura di modificare. Sforzandosi per abstrazioni a costo zero, caratteristiche di livello superiore che si compilano in codice di livello inferiore veloce come il codice scritto manualmente, Rust si sforza di rendere il codice sicuro anche il codice veloce.
Si spera che il linguaggio Rust supporti anche molti altri utenti; quelli menzionati qui sono semplicemente alcuni dei maggiori stakeholder. Nel complesso, l'ambizione più grande di Rust è quella di eliminare i compromessi che i programmatori hanno accettato per decenni fornendo sicurezza e produttività, velocità e ergonomia. Dai una prova a Rust e vedi se le sue scelte funzionano per te.
Per chi è questo libro
Questo libro presume che tu abbia scritto codice in un altro linguaggio di programmazione ma non fa supposizioni su quale. Abbiamo cercato di rendere il materiale ampiamente accessibile a coloro provenienti da una vasta gamma di background di programmazione. Non passiamo molto tempo a parlare di cosa sia la programmazione è o su come pensarci. Se sei del tutto nuovo alla programmazione, sarebbe meglio servito leggendo un libro che fornisce specificamente un'introduzione alla programmazione.
Come utilizzare questo libro
In generale, questo libro presuppone che tu lo stia leggendo in sequenza dall'inizio alla fine. I capitoli successivi si basano su concetti nei capitoli precedenti, e i capitoli precedenti potrebbero non approfondire i dettagli su un particolare argomento ma rivisiteranno l'argomento in un capitolo successivo.
Troverai due tipi di capitoli in questo libro: capitoli di concetti e capitoli di progetti. Nei capitoli di concetto, apprenderai un aspetto di Rust. Nei capitoli di progetto, costruiremo piccoli programmi insieme, applicando ciò che hai finora appreso. I capitoli 2, 12 e 20 sono capitoli di progetto; il resto sono capitoli di concetto.
Il Capitolo 1 spiega come installare Rust, come scrivere un programma "Hello, world!", e come usare Cargo, il gestore di pacchetti di Rust e strumento di compilazione. Il Capitolo 2 è un'introduzione pratica alla scrittura di un programma in Rust, facendoti costruire un gioco di indovinare numeri. Qui copriamo concetti ad alto livello, e i capitoli successivi forniranno dettagli aggiuntivi. Se vuoi sporcarti le mani subito, il Capitolo 2 è il luogo adatto per farlo. Il Capitolo 3 copre le funzionalità di Rust che sono simili a quelle di altri linguaggi di programmazione, e nel Capitolo 4 imparerai il sistema di Ownership di Rust. Se sei un apprendista particolarmente scrupoloso che preferisce imparare ogni dettaglio prima di passare al successivo, potresti voler saltare il Capitolo 2 e andare direttamente al Capitolo 3, tornando al Capitolo 2 quando vorrai lavorare su un progetto applicando i dettagli che hai appreso.
Il Capitolo 5 discute Structs e metodi, e il Capitolo 6 copre Enum, espressioni match
e l'istruzione di controllo del flusso if let
. Userai Structs e Enum per creare tipi personalizzati in Rust.
Nel Capitolo 7, imparerai il sistema dei moduli di Rust e le regole della privacy per organizzare il tuo codice e la sua pubblica Interfaccia di Programmazione dell'Applicazione (API). Il Capitolo 8 discute alcune comuni strutture di dati di collezioni che la la libreria standard fornisce, come i vettori, le stringhe e le mappe hash. Il Capitolo 9 esplora la filosofia e le tecniche di gestione degli errori di Rust.
Il Capitolo 10 approfondisce i generici, i traits, e i lifetimes, che ti danno il potere
di definire il codice che si applica a più tipi. Il Capitolo 11 riguarda tutti i test,
che anche con le garanzie di sicurezza di Rust sono necessari per assicurare la correttezza della logica del tuo programma.
Nel Capitolo 12, costruiremo la nostra implementazione di un sottoinsieme di funzionalità dal grep
comando da riga di comando che cerca testo
all'interno dei file. Per questo, utilizzeremo molti dei concetti che abbiamo discusso nei
capitoli precedenti.
Il Capitolo 13 esplora closures e iteratori: caratteristiche di Rust che provengono da linguaggi di programmazione funzionali. Nel Capitolo 14, esamineremo Cargo in più profondità e parleremo delle migliori pratiche per condividere le tue librerie con gli altri. Il Capitolo 15 discute i puntatori intelligenti che la libreria standard fornisce e i traits che abilitano le loro funzionalità.
Nel Capitolo 16, passeremo attraverso diversi modelli di programmazione concorrente e parleremo di come Rust ti aiuta a programmare in più thread senza paura. Il Capitolo 17 guarda come gli idiomi di Rust si confrontano con principi di programmazione orientata agli oggetti con cui potresti essere familiare.
Il Capitolo 18 è un riferimento sui pattern e il matching di pattern, che sono potenti modi di esprimere idee nei programmi Rust. Il Capitolo 19 contiene un assortimento di argomenti avanzati di interesse, tra cui Rust insicuro, macro, e altre informazioni su lifetimes, traits, tipi, funzioni e closures.
Nel Capitolo 20, completeremo un progetto in cui implementeremo un server web a basso livello multithread! Infine, alcuni appendici contengono informazioni utili sul linguaggio in un formato più simile a un riferimento. L'appendice A copre le parole chiave di Rust, l'appendice B copre gli operatori e i simboli di Rust, l'appendice C copre i trait derivabili forniti dalla libreria standard, l'appendice D copre alcuni strumenti di sviluppo utili, e l'appendice E spiega le edizioni di Rust. Nell'appendice F, puoi trovare traduzioni del libro, e nell'appendice G tratteremo come viene fatto Rust e cosa sia il Rust nightly.
Non c'è un modo sbagliato di leggere questo libro: se vuoi saltare avanti, fallo! Potresti dover tornare indietro ai capitoli precedenti se riscontri qualche confusione. Ma fai quello che funziona per te.
Una parte importante del processo di apprendimento del Rust è imparare a leggere i messaggi di errore che il compilatore visualizza: questi ti guideranno verso il codice funzionante. Come tale, forniremo molti esempi che non compilano insieme al messaggio di errore che il compilatore ti mostrerà in ogni situazione. Sappi che se inserisci ed esegui un esempio casuale, potrebbe non compilare! Assicurati di leggere il testo circostante per vedere se l'esempio che stai cercando di eseguire è destinato a generare un errore. Ferris ti aiuterà anche a distinguere il codice che non dovrebbe funzionare:
Ferris | Significato |
---|---|
Questo codice non compila! | |
Questo codice va in panic! | |
Questo codice non produce il comportamento desiderato. |
Nella maggior parte delle situazioni, ti guideremo verso la versione corretta di qualsiasi codice che non compila.
Codice Sorgente
I file sorgente da cui è generato questo libro possono essere trovati su GitHub.
Iniziare
Iniziamo il tuo viaggio con Rust! C'è molto da imparare, ma ogni viaggio inizia da qualche parte. In questo capitolo, discuteremo:
- Installare Rust su Linux, macOS e Windows
- Scrivere un programma che stampa
Hello, world!
- Utilizzare
cargo
, il gestore di pacchetti e sistema di build di Rust
Installazione
Il primo passo è installare Rust. Scaricheremo Rust tramite rustup
, uno
strumento da linea di comando per gestire le versioni di Rust e gli strumenti associati. Avrai bisogno di una connessione internet per il download.
Nota: Se preferisci non utilizzare
rustup
per qualche motivo, consulta la pagina Altri Metodi di Installazione di Rust per altre opzioni.
I seguenti passi installano l'ultima versione stabile del compilatore Rust. Le garanzie di stabilità di Rust assicurano che tutti gli esempi nel libro che compilano continueranno a compilare con le versioni più recenti di Rust. L'output potrebbe variare leggermente tra le versioni poiché Rust spesso migliora i messaggi di errore e di avvertimento. In altre parole, qualsiasi nuova versione stabile di Rust installata seguendo questi passi dovrebbe funzionare come previsto con il contenuto di questo libro.
Notazione della Linea di Comando
In questo capitolo e in tutto il libro, mostreremo alcuni comandi usati nel terminale. Le righe che dovresti inserire in un terminale iniziano tutte con
$
. Non hai bisogno di digitare il carattere$
; è il prompt della linea di comando mostrato per indicare l'inizio di ciascun comando. Le righe che non iniziano con$
tipicamente mostrano l'output del comando precedente. Inoltre, gli esempi specifici di PowerShell useranno>
anziché$
.
Installare rustup
su Linux o macOS
Se stai usando Linux o macOS, apri un terminale e inserisci il seguente comando:
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
Il comando scarica uno script e avvia l'installazione dello strumento rustup
,
che installa l'ultima versione stabile di Rust. Potresti essere invitato a
fornire la tua password. Se l'installazione è riuscita, verrà visualizzata la seguente riga:
Rust is installed now. Great!
Avrai anche bisogno di un linker, che è un programma che Rust utilizza per unire i suoi output compilati in un unico file. È probabile che tu ne abbia già uno. Se ottieni errori di linker, dovresti installare un compilatore C, che includerà tipicamente un linker. Un compilatore C è anche utile perché alcuni pacchetti Rust comuni dipendono dal codice C e avranno bisogno di un compilatore C.
Su macOS, puoi ottenere un compilatore C eseguendo:
$ xcode-select --install
Gli utenti Linux dovrebbero generalmente installare GCC o Clang, in base alla
documentazione della loro distribuzione. Ad esempio, se usi Ubuntu, puoi installare il pacchetto build-essential
.
Installare rustup
su Windows
Su Windows, vai a https://www.rust-lang.org/tools/install e segui le istruzioni per installare Rust. Ad un certo punto dell'installazione, ti verrà chiesto di installare Visual Studio. Questo fornisce un linker e le librerie native necessarie per compilare i programmi. Se hai bisogno di ulteriore assistenza con questo passaggio, consulta https://rust-lang.github.io/rustup/installation/windows-msvc.html
Il resto di questo libro utilizza comandi che funzionano sia in cmd.exe che in PowerShell. Se ci sono differenze specifiche, spiegheremo quale usare.
Risoluzione dei Problemi
Per verificare se hai installato correttamente Rust, apri una shell e inserisci questa riga:
$ rustc --version
Dovresti vedere il numero di versione, l'hash del commit e la data del commit per l'ultima versione stabile rilasciata, nel seguente formato:
rustc x.y.z (abcabcabc yyyy-mm-dd)
Se vedi queste informazioni, hai installato correttamente Rust! Se non vedi queste informazioni, verifica che Rust sia nella variabile di sistema %PATH%
come segue.
In CMD di Windows, usa:
> echo %PATH%
In PowerShell, usa:
> echo $env:Path
In Linux e macOS, usa:
$ echo $PATH
Se tutto ciò è corretto e Rust non funziona ancora, ci sono vari posti dove puoi ottenere aiuto. Scopri come entrare in contatto con altri Rustaceans (un soprannome scherzoso che ci diamo) sulla pagina della comunità.
Aggiornamento e Disinstallazione
Una volta che Rust è installato tramite rustup
, aggiornare a una versione rilasciata di recente è semplice. Dalla tua shell, esegui il seguente script di aggiornamento:
$ rustup update
Per disinstallare Rust e rustup
, esegui il seguente script di disinstallazione dalla tua shell:
$ rustup self uninstall
Documentazione Locale
L'installazione di Rust include anche una copia locale della documentazione in modo che tu possa leggerla offline. Esegui rustup doc
per aprire la documentazione locale nel tuo browser.
Ogni volta che un tipo o una funzione è fornita dalla libreria standard e non sei sicuro di cosa faccia o di come usarla, usa la documentazione dell'interfaccia di programmazione delle applicazioni (API) per approfondire!
Hello, World!
Ora che hai installato Rust, è il momento di scrivere il tuo primo programma in Rust.
È tradizione, quando si impara un nuovo linguaggio, scrivere un piccolo programma che stamperà il testo Hello, world!
sullo schermo, quindi faremo lo stesso qui!
Nota: Questo libro presume una familiarità di base con la riga di comando. Rust non richiede nulla di specifico riguardo l'editor o gli strumenti o dove il codice risiede, quindi se preferisci usare un ambiente di sviluppo integrato (IDE) invece della riga di comando, sentiti libero di utilizzare il tuo IDE preferito. Molti IDE ora hanno un certo grado di supporto per Rust; controlla la documentazione dell'IDE per i dettagli. Il team di Rust si è concentrato nel fornire un ottimo supporto per gli IDE tramite
rust-analyzer
. Vedi Appendice D per maggiori dettagli.
Creazione di una Directory di Progetto
Inizierai creando una directory per conservare il tuo codice Rust. Non importa a Rust dove risiede il tuo codice, ma per gli esercizi e i progetti in questo libro, suggeriamo di creare una directory projects nella tua home directory e di conservare lì tutti i tuoi progetti.
Apri un terminale ed entra i seguenti comandi per creare una directory projects e una directory per il progetto "Hello, world!" all'interno della directory projects.
Per Linux, macOS e PowerShell su Windows, inserisci questo:
$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
Per Windows CMD, inserisci questo:
> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir hello_world
> cd hello_world
Scrivere ed Eseguire un Programma Rust
Successivamente, crea un nuovo file sorgente chiamato main.rs. I file Rust terminano sempre con l'estensione .rs. Se stai usando più di una parola nel nome del file, la convenzione è usare un trattino basso per separarle. Ad esempio, usa hello_world.rs piuttosto che helloworld.rs.
Ora apri il file main.rs che hai appena creato e inserisci il codice elencato in Listing 1-1.
fn main() { println!("Hello, world!"); }
Salva il file e torna alla tua finestra del terminale nella directory ~/projects/hello_world. Su Linux o macOS, inserisci i seguenti comandi per compilare ed eseguire il file:
$ rustc main.rs
$ ./main
Hello, world!
Su Windows, inserisci il comando .\main.exe
invece di ./main
:
> rustc main.rs
> .\main.exe
Hello, world!
Indipendentemente dal tuo sistema operativo, la stringa Hello, world!
dovrebbe essere stampata sul terminale. Se non vedi questo output, torna alla parte “Risoluzione dei problemi” della sezione di Installazione per trovare modalità per ottenere aiuto.
Se Hello, world!
è stato stampato, congratulazioni! Hai ufficialmente scritto un programma in Rust. Questo ti rende un programmatore Rust—benvenuto!
Anatomia di un Programma Rust
Esaminiamo in dettaglio questo programma "Hello, world!". Ecco la prima parte del puzzle:
fn main() { }
Queste righe definiscono una funzione chiamata main
. La funzione main
è speciale: è sempre il primo codice che viene eseguito in ogni programma Rust eseguibile. Qui, la prima riga dichiara una funzione chiamata main
che non ha parametri e non restituisce nulla. Se ci fossero parametri, andrebbero inseriti tra parentesi ()
.
Il corpo della funzione è racchiuso tra {}
. Rust richiede parentesi graffe intorno a tutti i corpi delle funzioni. È buona norma posizionare la parentesi graffa di apertura sulla stessa linea della dichiarazione della funzione, aggiungendo uno spazio tra i due.
Nota: Se desideri aderire a uno stile standard tra i progetti Rust, puoi utilizzare uno strumento di formattazione automatico chiamato
rustfmt
per formattare il tuo codice in uno stile particolare (maggiori informazioni surustfmt
si trovano in Appendice D). Il team di Rust ha incluso questo strumento con la distribuzione standard di Rust, così comerustc
, quindi dovrebbe essere già installato sul tuo computer!
Il corpo della funzione main
contiene il seguente codice:
#![allow(unused)] fn main() { println!("Hello, world!"); }
Questa linea fa tutto il lavoro in questo piccolo programma: stampa del testo sullo schermo. Ci sono quattro dettagli importanti da notare qui.
Primo, lo stile Rust è di indentare con quattro spazi, non con una tabulazione.
Secondo, println!
chiama una macro di Rust. Se avesse chiamato una funzione invece, sarebbe stato println
(senza il !
). Discuteremo delle macro di Rust in maggiore dettaglio nel Capitolo 19. Per ora, devi solo sapere che usare un !
significa che stai chiamando una macro invece di una funzione normale e che le macro non seguono sempre le stesse regole delle funzioni.
Terzo, vedi la stringa "Hello, world!"
. Passiamo questa stringa come argomento a println!
, e la stringa viene stampata sullo schermo.
Quarto, terminiamo la riga con un punto e virgola (;
), che indica che questa espressione è terminata e la prossima è pronta per iniziare. La maggior parte delle righe di codice Rust termina con un punto e virgola.
Compilare ed Eseguire Sono Passi Separati
Hai appena eseguito un programma appena creato, quindi esaminiamo ogni passo del processo.
Prima di eseguire un programma Rust, devi compilarlo usando il compilatore di Rust inserendo il comando rustc
e passandogli il nome del tuo file sorgente, come questo:
$ rustc main.rs
Se hai una base di conoscenze su C o C++, noterai che è simile a gcc
o clang
. Dopo aver compilato con successo, Rust emette un eseguibile binario.
Su Linux, macOS e PowerShell su Windows, puoi vedere l'eseguibile inserendo il comando ls
nella tua shell:
$ ls
main main.rs
Su Linux e macOS, vedrai due file. Con PowerShell su Windows, vedrai gli stessi tre file che vedresti usando CMD. Con CMD su Windows, inseriresti il seguente comando:
> dir /B %= l'opzione /B dice di mostrare solo i nomi dei file =%
main.exe
main.pdb
main.rs
Questo mostra il file sorgente con l'estensione .rs, il file eseguibile (main.exe su Windows, ma main su tutte le altre piattaforme), e, su Windows, un file contenente informazioni di debug con l'estensione .pdb. Da qui, esegui il file main o main.exe, in questo modo:
$ ./main # o .\main.exe su Windows
Se il tuo main.rs è il tuo programma “Hello, world!”, questa linea stamperà Hello, world!
sul tuo terminale.
Se sei più familiare con un linguaggio dinamico, come Ruby, Python o JavaScript, potresti non essere abituato a compilare ed eseguire un programma come passaggi separati. Rust è un linguaggio compilato in anticipo, il che significa che puoi compilare un programma e dare l'eseguibile a qualcun altro, e potranno eseguirlo anche senza avere Rust installato. Se dai a qualcuno un file .rb, .py, o .js, deve avere un'implementazione di Ruby, Python o JavaScript installata (rispettivamente). Ma in quei linguaggi, hai bisogno solo di un comando per compilare ed eseguire il tuo programma. Tutto è un compromesso nel design del linguaggio.
Compilare con rustc
va bene per programmi semplici, ma man mano che il tuo progetto cresce, vorrai gestire tutte le opzioni e rendere facile la condivisione del tuo codice. Successivamente, ti presenteremo lo strumento Cargo, che ti aiuterà a scrivere programmi Rust per il mondo reale.
Ciao, Cargo!
Cargo è il sistema di build e il gestore di pacchetti di Rust. La maggior parte dei Rustaceans utilizza questo strumento per gestire i propri progetti Rust perché Cargo gestisce molte attività per te, come la compilazione del tuo codice, il download delle librerie da cui dipende il tuo codice e la compilazione di queste librerie. (Chiamiamo le librerie di cui il tuo codice ha bisogno dipendenze.)
I programmi Rust più semplici, come quello che abbiamo scritto finora, non hanno dipendenze. Se avessimo costruito il progetto "Hello, world!" con Cargo, avrebbe usato solo la parte di Cargo che gestisce la compilazione del tuo codice. Man mano che scrivi programmi Rust più complessi, aggiungerai dipendenze, e se inizi un progetto usando Cargo, aggiungere dipendenze sarà molto più facile.
Poiché la stragrande maggioranza dei progetti Rust utilizza Cargo, il resto di questo libro presuppone che tu stia usando Cargo. Cargo viene installato con Rust se hai utilizzato gli installer ufficiali discussi nella sezione “Installazione”. Se hai installato Rust tramite altri metodi, verifica se Cargo è installato inserendo il seguente comando nel tuo terminale:
$ cargo --version
Se visualizzi un numero di versione, significa che è installato! Se visualizzi un errore, come command not found
, consulta la documentazione per il metodo di installazione utilizzato per determinare come installare Cargo separatamente.
Creare un Progetto con Cargo
Creiamo un nuovo progetto usando Cargo e vediamo come differisce dal nostro progetto originale "Hello, world!". Torna alla tua directory projects (o ovunque tu abbia deciso di archiviare il tuo codice). Quindi, su qualsiasi sistema operativo, esegui il seguente comando:
$ cargo new hello_cargo
$ cd hello_cargo
Il primo comando crea una nuova directory e progetto chiamato hello_cargo. Abbiamo chiamato il nostro progetto hello_cargo, e Cargo crea i suoi file in una directory con lo stesso nome.
Entra nella directory hello_cargo e elenca i file. Vedrai che Cargo ha generato due file e una directory per noi: un file Cargo.toml e una directory src con un file main.rs all'interno.
Ha anche inizializzato un nuovo repository Git assieme a un file .gitignore. I file Git non verranno generati se esegui cargo new
all'interno di un repository Git esistente; puoi ignorare questo comportamento usando cargo new --vcs=git
.
Nota: Git è un sistema di controllo di versione comune. Puoi modificare
cargo new
per utilizzare un sistema di controllo di versione diverso o nessun sistema di controllo di versione utilizzando il flag--vcs
. Eseguicargo new --help
per vedere le opzioni disponibili.
Apri Cargo.toml nel tuo editor di testo preferito. Dovrebbe apparire simile al codice nel Listing 1-2.
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# Guarda più chiavi e le loro definizioni su https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Questo file è nel formato TOML (Tom’s Obvious, Minimal Language), che è il formato di configurazione di Cargo.
La prima riga, [package]
, è un'intestazione di sezione che indica che le dichiarazioni seguenti configurano un pacchetto. Man mano che aggiungiamo più informazioni a questo file, aggiungeremo altre sezioni.
Le successive tre righe impostano le informazioni di configurazione di cui Cargo ha bisogno per compilare il tuo programma: il nome, la versione e l'edizione di Rust da utilizzare. Parleremo della chiave edition
nell'Appendice E.
L'ultima riga, [dependencies]
, è l'inizio di una sezione in cui elencare eventuali dipendenze del tuo progetto. In Rust, i pacchetti di codice sono denominati crates. Non avremo bisogno di altri crates per questo progetto, ma ne avremo bisogno nel primo progetto del Capitolo 2, quindi utilizzeremo questa sezione delle dipendenze allora.
Ora apri src/main.rs e dai un'occhiata:
Nome del file: src/main.rs
fn main() { println!("Hello, world!"); }
Cargo ha generato un programma “Hello, world!” per te, proprio come quello che abbiamo scritto nel Listing 1-1! Fino ad ora, le differenze tra il nostro progetto e il progetto generato da Cargo sono che Cargo ha inserito il codice nella directory src e abbiamo un file di configurazione Cargo.toml nella directory principale.
Cargo si aspetta che i tuoi file sorgente risiedano all'interno della directory src. La directory del progetto di livello superiore è solo per i file README, le informazioni sulla licenza, i file di configurazione e tutto ciò che non è correlato al tuo codice. Usare Cargo ti aiuta a organizzare i tuoi progetti. C'è un posto per tutto, e tutto è al suo posto.
Se hai iniziato un progetto che non utilizza Cargo, come abbiamo fatto con il progetto "Hello, world!", puoi convertirlo in un progetto che utilizza Cargo. Sposta il codice del progetto nella directory src e crea un file Cargo.toml appropriato.
Compilare ed Eseguire un Progetto Cargo
Ora vediamo cosa cambia quando compiliamo ed eseguiamo il programma “Hello, world!” con Cargo! Dalla tua directory hello_cargo, compila il tuo progetto inserendo il seguente comando:
$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs
Questo comando crea un file eseguibile in target/debug/hello_cargo (o target\debug\hello_cargo.exe su Windows) anziché nella tua directory corrente. Poiché la build predefinita è una build di debug, Cargo mette il binario in una directory chiamata debug. Puoi eseguire l'eseguibile con questo comando:
$ ./target/debug/hello_cargo # o .\target\debug\hello_cargo.exe su Windows
Hello, world!
Se tutto va bene, Hello, world!
dovrebbe apparire nel terminale. L'esecuzione di cargo build
per la prima volta fa sì che Cargo crei anche un nuovo file a livello principale: Cargo.lock. Questo file tiene traccia delle versioni esatte delle dipendenze nel tuo progetto. Questo progetto non ha dipendenze, quindi il file è un po' scarso. Non dovrai mai modificare manualmente questo file; Cargo gestisce il suo contenuto per te.
Abbiamo appena compilato un progetto con cargo build
e l'abbiamo eseguito con ./target/debug/hello_cargo
, ma possiamo anche utilizzare cargo run
per compilare il codice e poi eseguire l'eseguibile risultante tutto in un solo comando:
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/hello_cargo`
Hello, world!
Utilizzare cargo run
è più conveniente che dover ricordare di eseguire cargo build
e poi utilizzare l'intero percorso del binario, quindi la maggior parte degli sviluppatori utilizza cargo run
.
Nota che questa volta non abbiamo visto un output che indicasse che Cargo stava compilando hello_cargo
. Cargo ha capito che i file non erano cambiati, quindi non ha ricompilato ma semplicemente ha eseguito il binario. Se avessi modificato il tuo codice sorgente, Cargo avrebbe ricompilato il progetto prima di eseguirlo e avresti visto questo output:
$ cargo run
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs
Running `target/debug/hello_cargo`
Hello, world!
Cargo fornisce anche un comando chiamato cargo check
. Questo comando controlla rapidamente il tuo codice per assicurarsi che si compili ma non produce un eseguibile:
$ cargo check
Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs
Perché potresti non volere un eseguibile? Spesso, cargo check
è molto più veloce di cargo build
perché salta il passaggio di produzione di un eseguibile. Se stai controllando continuamente il tuo lavoro durante la scrittura del codice, utilizzare cargo check
accelererà il processo di informarti se il tuo progetto si compila ancora! Così, molti Rustaceans eseguono cargo check
periodicamente mentre scrivono i loro programmi per assicurarsi che si compilino. Quindi eseguono cargo build
quando sono pronti per utilizzare l'eseguibile.
Ricapiamo cosa abbiamo imparato finora su Cargo:
- Possiamo creare un progetto usando
cargo new
. - Possiamo costruire un progetto usando
cargo build
. - Possiamo costruire ed eseguire un progetto in un solo passaggio usando
cargo run
. - Possiamo costruire un progetto senza produrre un binario per controllare gli errori usando
cargo check
. - Invece di salvare il risultato della build nella stessa directory del nostro codice, Cargo lo memorizza nella directory target/debug.
Un ulteriore vantaggio di utilizzare Cargo è che i comandi sono gli stessi indipendentemente dal sistema operativo su cui stai lavorando. Quindi, a questo punto, non forniremo più istruzioni specifiche per Linux e macOS rispetto a Windows.
Compilare per il Rilascio
Quando il tuo progetto è finalmente pronto per il rilascio, puoi utilizzare cargo build --release
per compilarlo con ottimizzazioni. Questo comando creerà un eseguibile in target/release invece di target/debug. Le ottimizzazioni fanno eseguire il codice Rust più velocemente, ma attivarle allunga il tempo necessario per compilare il tuo programma. Questo è il motivo per cui ci sono due profili differenti: uno per lo sviluppo, quando vuoi ricostruire rapidamente e spesso, e un altro per costruire il programma finale che darai a un utente che non verrà ricostruito ripetutamente e che verrà eseguito il più velocemente possibile. Se stai facendo benchmarking del tempo di esecuzione del tuo codice, assicurati di eseguire cargo build --release
e fare il benchmarking con l'eseguibile in target/release.
Cargo come Convenzione
Con progetti semplici, Cargo non fornisce molto valore rispetto a solo utilizzare rustc
, ma dimostrerà il suo valore man mano che i tuoi programmi diventeranno più intricati. Una volta che i programmi crescono a più file o hanno bisogno di una dipendenza, è molto più facile lasciare che Cargo coordini la build.
Anche se il progetto hello_cargo
è semplice, ora utilizza gran parte degli strumenti reali che utilizzerai nel resto della tua carriera con Rust. Infatti, per lavorare su eventuali progetti esistenti, puoi utilizzare i seguenti comandi per controllare il codice usando Git, passare alla directory di quel progetto e costruirlo:
$ git clone example.org/someproject
$ cd someproject
$ cargo build
Per ulteriori informazioni su Cargo, consulta la sua documentazione.
Riepilogo
Hai già iniziato alla grande il tuo viaggio con Rust! In questo capitolo, hai imparato a:
- Installare l'ultima versione stabile di Rust usando
rustup
- Aggiornare a una nuova versione di Rust
- Aprire la documentazione installata localmente
- Scrivere ed eseguire un programma “Hello, world!” utilizzando
rustc
direttamente - Creare ed eseguire un nuovo progetto usando le convenzioni di Cargo
Questo è un ottimo momento per costruire un programma più sostanziale per abituarti a leggere e scrivere codice Rust. Quindi, nel Capitolo 2, costruiremo un programma di gioco di indovinelli. Se preferisci iniziare imparando come funzionano i concetti di programmazione comuni in Rust, consulta il Capitolo 3 e poi torna al Capitolo 2.
Programmare un Gioco di Indovinelli
Immergiamoci in Rust lavorando a un progetto pratico insieme! Questo capitolo ti introduce ad alcuni concetti comuni di Rust mostrandoti come usarli in un programma reale. Imparerai a conoscere let
, match
, metodi, funzioni associate, crate esterni e altro ancora! Nei capitoli seguenti, esploreremo questi concetti in dettaglio. In questo capitolo, ti eserciterai solo sui fondamentali.
Implementeremo un classico problema di programmazione per principianti: un gioco di indovinelli. Ecco come funziona: il programma genererà un numero intero casuale tra 1 e 100. Quindi inviterà il giocatore a inserire un indovinello. Dopo che è stato inserito, il programma indicherà se l’indovinello è troppo basso o troppo alto. Se l’indovinello è corretto, il gioco stamperà un messaggio di congratulazioni e uscirà.
Configurare un Nuovo Progetto
Per configurare un nuovo progetto, vai nella directory projects che hai creato nel Capitolo 1 e crea un nuovo progetto utilizzando Cargo, così:
$ cargo new guessing_game
$ cd guessing_game
Il primo comando, cargo new
, prende il nome del progetto (guessing_game
) come primo argomento. Il secondo comando cambia nella directory del nuovo progetto.
Guarda il file Cargo.toml generato:
Nome del file: Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Come hai visto nel Capitolo 1, cargo new
genera un programma “Hello, world!” per te. Controlla il file src/main.rs:
Nome del file: src/main.rs
fn main() { println!("Hello, world!"); }
Ora compiliamo questo programma “Hello, world!” e eseguiamolo nello stesso passo usando il comando cargo run
:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/guessing_game`
Hello, world!
Il comando run
è utile quando hai bisogno di iterare rapidamente su un progetto, come faremo in questo gioco, testando velocemente ogni iterazione prima di passare a quella successiva.
Riapri il file src/main.rs. Scriverai tutto il codice in questo file.
Elaborare un Indovinello
La prima parte del programma del gioco di indovinelli chiederà l'input dell'utente, elaborerà tale input e controllerà che l'input sia nella forma prevista. Per iniziare, permetteremo al giocatore di inserire un indovinello. Inserisci il codice nel Listing 2-1 in src/main.rs.
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Questo codice contiene molte informazioni, quindi esaminiamolo riga per riga. Per ottenere l'input dell'utente e quindi stampare il risultato come output, dobbiamo importare la libreria di input/output io
nello Scope. La libreria io
proviene dalla libreria standard, conosciuta come std
:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Per impostazione predefinita, Rust ha un insieme di elementi definiti nella libreria standard che include nello Scope di ogni programma. Questo insieme è chiamato prelude, e puoi vedere tutto ciò che contiene nella documentazione della libreria standard.
Se il tipo che vuoi usare non è nel prelude, devi importerlo esplicitamente nello Scope con un'istruzione use
. Usare la libreria std::io
ti fornisce un numero di funzionalità utili, inclusa la possibilità di accettare l'input dell'utente.
Come hai visto nel Capitolo 1, la funzione main
è il punto d'ingresso nel programma:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
La sintassi fn
dichiara una nuova funzione; le parentesi, ()
, indicano che non ci sono parametri; e le parentesi graffe, {
, iniziano il corpo della funzione.
Come hai anche imparato nel Capitolo 1, println!
è una macro che stampa una stringa sullo schermo:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Questo codice sta stampando un prompt che indica qual è il gioco e richiede input dall’utente.
Memorizzare i Valori con le Variabili
Successivamente, creeremo una variabile per memorizzare l’input dell’utente, come questo:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Ora il programma sta diventando interessante! C’è molto in questa piccola riga. Usiamo l'istruzione let
per creare la variabile. Ecco un altro esempio:
let apples = 5;
Questa riga crea una nuova variabile chiamata apples
e la lega al valore 5. In Rust, le variabili sono immutabili per impostazione predefinita, il che significa che una volta assegnato il valore alla variabile, il valore non cambierà. Discuteremo questo concetto in dettaglio nella sezione “Variabili e Mutabilità” nel Capitolo 3. Per rendere una variabile mutabile, aggiungiamo mut
prima del nome della variabile:
let apples = 5; // immutabile
let mut bananas = 5; // mutabile
Nota: La sintassi
//
inizia un commento che continua fino alla fine della riga. Rust ignora tutto nei commenti. Discuteremo i commenti in modo più dettagliato nel Capitolo 3.
Ritornando al programma di gioco di indovinelli, ora sai che let mut guess
introdurrà una variabile mutabile chiamata guess
. Il segno di uguale (=
) dice a Rust che vogliamo legare qualcosa alla variabile ora. A destra del segno di uguale c'è il valore a cui guess
è legato, che è il risultato della chiamata a String::new
, una funzione che restituisce una nuova istanza di una String
. String
è un tipo di stringa fornito dalla libreria standard che è un testo UTF-8 espandibile.
La sintassi ::
nella riga ::new
indica che new
è una funzione associata al tipo String
. Una funzione associata è una funzione che è implementata su un tipo, in questo caso String
. Questa funzione new
crea una nuova stringa vuota. Troverai una funzione new
su molti tipi perché è un nome comune per una funzione che crea un nuovo valore di qualche tipo.
In sintesi, la riga let mut guess = String::new();
ha creato una variabile mutabile che è attualmente legata a una nuova istanza vuota di una String
. Uffa!
Ricevere Input dall’Utente
Ricorda che abbiamo incluso la funzionalità di input/output dalla libreria standard con use std::io;
nella prima riga del programma. Ora chiameremo la funzione stdin
dal modulo io
, che ci permetterà di gestire l'input dell'utente:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Se non avessimo importato la libreria io
con use std::io;
all'inizio del programma, potremmo ancora usare la funzione scrivendo questa chiamata di funzione come std::io::stdin
. La funzione stdin
restituisce un'istanza di std::io::Stdin
, che è un tipo che rappresenta un handle all'input standard per il tuo terminale.
Successivamente, la riga .read_line(&mut guess)
chiama il metodo read_line
sull'handle dell'input standard per ottenere l'input dall'utente. Stiamo anche passando &mut guess
come argomento a read_line
per dirgli in quale stringa memorizzare l’input dell’utente. Il compito completo di read_line
è prendere qualsiasi cosa l’utente digiti nell’input standard e aggiungerla a una stringa (senza sovrascriverne i contenuti), quindi passiamo quella stringa come argomento. L’argomento della stringa deve essere mutabile affinché il metodo possa cambiare il contenuto della stringa.
Il &
indica che questo argomento è un reference, il che ti dà un modo per permettere a più parti del tuo codice di accedere a un pezzo di dati senza dover copiare quei dati in memoria più volte. I reference sono una caratteristica complessa, e uno dei grandi vantaggi di Rust è quanto sia sicuro e facile usare i reference. Non hai bisogno di sapere molti di questi dettagli per finire questo programma. Per ora, tutto ciò che devi sapere è che, come le variabili, i reference sono immutabili per impostazione predefinita. Pertanto, devi scrivere &mut guess
anziché &guess
per renderlo mutabile. (Il Capitolo 4 spiegherà i reference più approfonditamente.)
Gestione di Potenziali Errori con Result
Stiamo ancora lavorando su questa riga di codice. Stiamo ora discutendo una terza riga di testo, ma nota che fa ancora parte di una singola riga logica di codice. La parte successiva è questo metodo:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Avremmo potuto scrivere questo codice come:
io::stdin().read_line(&mut guess).expect("Failed to read line");
Tuttavia, una riga lunga è difficile da leggere, quindi è meglio dividerla. È spesso saggio introdurre un'interruzione di riga e altri spazi bianchi per aiutare a suddividere le righe lunghe quando si chiama un metodo con la sintassi .method_name()
. Ora discutiamo cosa fa questa riga.
Come menzionato prima, read_line
inserisce qualsiasi cosa l’utente inserisca nella stringa che gli passiamo, ma restituisce anche un valore Result
. Result
è una enumerazione, spesso chiamata enum, che è un tipo che può essere in uno dove multiple possibili stati. Chiamiamo ciascun possibile stato una variante.
Il Capitolo 6 coprirà le enum in modo più dettagliato. Lo scopo di questi tipi Result
è codificare informazioni sulla gestione degli errori.
Le varianti di Result
sono Ok
e Err
. La variante Ok
indica che l'operazione è stata eseguita con successo e all'interno di Ok
c'è il valore generato con successo. La variante Err
significa che l'operazione è fallita, e Err
contiene informazioni su come o perché l'operazione è fallita.
I valori del tipo Result
, come i valori di qualsiasi tipo, hanno metodi definiti su di essi. Un'istanza di Result
ha un metodo expect
che puoi chiamare. Se questa istanza di Result
è un valore Err
, expect
causerà il crash del programma e visualizzerà il messaggio che hai passato come argomento a expect
. Se il metodo read_line
restituisce un Err
, probabilmente sarà il risultato di un errore proveniente dal sistema operativo sottostante. Se questa istanza di Result
è un valore Ok
, expect
prenderà il valore restituito che Ok
sta mantenendo e restituirà solo quel valore in modo che tu possa usarlo. In questo caso, quel valore è il numero di byte nell’input dell’utente.
Se non chiami expect
, il programma verrà compilato, ma riceverai un avviso:
$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
warning: unused `Result` that must be used
--> src/main.rs:10:5
|
10 | io::stdin().read_line(&mut guess);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
warning: `guessing_game` (bin "guessing_game") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.59s
Rust avverte che non hai usato il valore Result
restituito da read_line
, indicando che il programma non ha gestito un possibile errore.
Il modo giusto per sopprimere l’avviso è scrivere effettivamente il codice per la gestione degli errori, ma nel nostro caso vogliamo solo che questo programma vada in crash quando si verifica un problema, quindi possiamo usare expect
. Imparerai a gestire il recupero dagli errori nel Capitolo 9.
Stampare Valori con i Segnaposto println!
A parte la parentesi graffa di chiusura, c'è solo un'altra riga di cui discutere nel codice finora:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Questa riga stampa la stringa che ora contiene l’input dell’utente. Il set di parentesi graffe {}
è un segnaposto: pensa a {}
come a piccole chele di granchio che tengono in posizione un valore. Quando stampi il valore di una variabile, il nome della variabile può andare all'interno delle parentesi graffe. Quando stampi il risultato della valutazione di un’espressione, inserisci parentesi graffe vuote nella stringa di formato, poi segui la stringa di formato con una lista di espressioni separate da virgole da stampare in ogni segnaposto di parentesi graffe vuote nello stesso ordine. Stampare una variabile e il risultato di un’espressione in una chiamata a println!
sembrerebbe così:
#![allow(unused)] fn main() { let x = 5; let y = 10; println!("x = {x} and y + 2 = {}", y + 2); }
Questo codice stamperebbe x = 5 and y + 2 = 12
.
Testare la Prima Parte
Testiamo la prima parte del gioco di indovinelli. Eseguilo usando cargo run
:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 6.44s
Running `target/debug/guessing_game`
Indovina il numero!
Per favore, inserisci il tuo indovinello.
6
Hai indovinato: 6
A questo punto, la prima parte del gioco è fatta: stiamo ottenendo l’input dalla tastiera e poi lo stiamo stampando.
Generare un Numero Segreto
Successivamente, dobbiamo generare un numero segreto che l’utente tenterà di indovinare. Il numero segreto dovrebbe essere diverso ogni volta in modo che il gioco sia divertente da giocare più di una volta. Utilizzeremo un numero casuale tra 1 e 100 in modo che il gioco non sia troppo difficile. Rust non include ancora la funzionalità per i numeri casuali nella sua libreria standard. Tuttavia, il team di Rust fornisce un crate rand
con quella funzionalità.
Utilizzare un Crate per Ottenere Più Funzionalità
Ricorda che un crate è una raccolta di file di codice sorgente Rust. Il progetto che abbiamo costruito è un crate binario, che è un eseguibile. Il crate rand
è un crate libreria, che contiene codice destinato a essere usato in altri programmi e non può essere eseguito da solo.
Il coordinamento di Cargo con i crate esterni è dove Cargo brilla davvero. Prima di poter scrivere codice che utilizzi rand
, dobbiamo modificare il file Cargo.toml per includere il crate rand
come dipendenza. Apri quel file ora e aggiungi la seguente riga in fondo, sotto l’intestazione della sezione [dependencies]
che Cargo ha creato per te. Assicurati di specificare rand
esattamente come abbiamo fatto qui, con questa versione, altrimenti gli esempi di codice in questo tutorial potrebbero non funzionare:
Nome del file: Cargo.toml
[dependencies]
rand = "0.8.5"
Nel file Cargo.toml, tutto ciò che segue un'intestazione fa parte di quella sezione che continua fino a quando non inizia un'altra sezione. In [dependencies]
indichi a Cargo di quali crate esterni il tuo progetto dipende e quali versioni di quei crate richiedi. In questo caso, specifichiamo il crate rand
con lo specificatore di versione semantica 0.8.5
. Cargo comprende il versionamento semantico (a volte chiamato SemVer), che è uno standard per scrivere i numeri di versione. Lo specificatore 0.8.5
è in realtà una scorciatoia per ^0.8.5
, il che significa qualsiasi versione almeno 0.8.5 ma inferiore a 0.9.0.
Cargo considera queste versioni come aventi API pubbliche compatibili con la versione 0.8.5, e questa specifica assicura che otterrai l'ultima release della patch che continuerà a compilare con il codice in questo capitolo. Qualsiasi versione 0.9.0 o superiore non è garantita di avere la stessa API di quanto usato nei seguenti esempi.
Ora, senza modificare alcun codice, costruiamo il progetto, come mostrato nel Listing 2-2.
$ cargo build
Updating crates.io index
Downloaded rand v0.8.5
Downloaded libc v0.2.127
Downloaded getrandom v0.2.7
Downloaded cfg-if v1.0.0
Downloaded ppv-lite86 v0.2.16
Downloaded rand_chacha v0.3.1
Downloaded rand_core v0.6.3
Compiling libc v0.2.127
Compiling getrandom v0.2.7
Compiling cfg-if v1.0.0
Compiling ppv-lite86 v0.2.16
Compiling rand_core v0.6.3
Compiling rand_chacha v0.3.1
Compiling rand v0.8.5
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53s
Potresti vedere numeri di versione diversi (ma saranno comunque compatibili con il codice, grazie a SemVer!) e linee diverse (a seconda del sistema operativo), e le linee potrebbero essere in un ordine diverso.
Quando includiamo una dipendenza esterna, Cargo preleva le versioni più recenti di tutto ciò che quella dipendenza necessita dal registro, che è una copia di dati da Crates.io. Crates.io è dove le persone nell'ecosistema Rust pubblicano i loro progetti Rust open source affinché altri possano utilizzarli.
Dopo aver aggiornato il registro, Cargo controlla la sezione [dependencies]
e scarica qualsiasi crate elencato che non sia già stato scaricato. In questo caso, anche se abbiamo elencato solo rand
come dipendenza, Cargo ha anche preso altri crate di cui rand
dipende per funzionare. Dopo aver scaricato i crate, Rust li compila e poi compila il progetto con le dipendenze disponibili.
Se esegui immediatamente cargo build
di nuovo senza fare alcuna modifica, non otterrai alcun output oltre alla riga Finished
. Cargo sa che ha già scaricato e compilato le dipendenze e non hai cambiato nulla nel tuo file Cargo.toml. Cargo sa anche che non hai cambiato nulla del tuo codice, quindi non ricompila neanche quello. Non avendo nulla da fare, semplicemente esce.
Se apri il file src/main.rs, fai una modifica banale e poi lo salvi e lo ricostruisci, vedrai solo due righe di output:
$ cargo build
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
Queste righe mostrano che Cargo aggiorna solo la build con il tuo piccolo cambiamento al file src/main.rs. Le tue dipendenze non sono cambiate, quindi Cargo sa che può riutilizzare ciò che ha già scaricato e compilato per quelle.
Garantire Build Riproducibili con il File Cargo.lock
Cargo ha un meccanismo che assicura che tu possa ricostruire lo stesso artefatto ogni volta che tu o qualcun altro costruite il tuo codice: Cargo utilizzerà solo le versioni delle dipendenze che hai specificato finché non indicherai diversamente. Per esempio, supponiamo che la prossima settimana esca la versione 0.8.6 del crate rand
, e che quella versione contenga una correzione importante di un bug, ma contenga anche una regressione che romperà il tuo codice. Per gestire questo, Rust crea il file Cargo.lock la prima volta che esegui cargo build
, quindi ora abbiamo questo nella directory guessing_game.
Quando costruisci un progetto per la prima volta, Cargo determina tutte le versioni delle dipendenze che soddisfano i criteri e poi le scrive nel file Cargo.lock. Quando costruisci il tuo progetto in futuro, Cargo vedrà che il file Cargo.lock esiste e utilizzerà le versioni specificate lì piuttosto che fare tutto il lavoro di determinare di nuovo le versioni. Questo ti permette di avere una build riproducibile automaticamente. In altre parole, il tuo progetto rimarrà alla versione 0.8.5 finché non esegui un aggiornamento esplicito, grazie al file Cargo.lock. Poiché il file Cargo.lock è importante per build riproducibili, spesso è incluso nel controllo del codice sorgente insieme al resto del codice del tuo progetto.
Aggiornare un Crate per Ottenere una Nuova Versione
Quando vuoi aggiornare un crate, Cargo fornisce il comando update
, che ignorerà il file Cargo.lock e determinerà tutte le versioni più recenti che soddisfano le tue specifiche in Cargo.toml. Cargo scriverà quindi quelle versioni nel file Cargo.lock. In questo caso, Cargo cercherà solo versioni maggiori di 0.8.5 e minori di 0.9.0. Se il crate rand
ha rilasciato le due nuove versioni 0.8.6 e 0.9.0, vedresti quanto segue se eseguissi cargo update
:
$ cargo update
Updating crates.io index
Updating rand v0.8.5 -> v0.8.6
Cargo ignora la release 0.9.0. A questo punto, noteresti anche una modifica nel file Cargo.lock che indica che la versione del crate rand
che stai ora utilizzando è la 0.8.6. Per utilizzare la versione 0.9.0 di rand
o qualsiasi versione nella serie 0.9.x, dovresti aggiornare il file Cargo.toml per assomigliare a questo:
[dependencies]
rand = "0.9.0"
La prossima volta che esegui cargo build
, Cargo aggiornerà il registro dei crate disponibili e rivaluterà i tuoi requisiti di rand
in base alla nuova versione che hai specificato.
C'è molto altro da dire su Cargo e [il suo ecosistema][doccratesio], di cui discuteremo nel Capitolo 14, ma per ora, questo è tutto quello che devi sapere. Cargo rende molto facile riutilizzare le librerie, quindi i Rustaceans possono scrivere progetti più piccoli che sono assemblati da un numero di pacchetti.
Generare un Numero Casuale
Iniziamo a usare rand
per generare un numero da indovinare. Il prossimo passo è aggiornare src/main.rs, come mostrato nel Listing 2-3.
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Per prima cosa aggiungiamo la riga use rand::Rng;
. Il trait Rng
definisce i metodi che i generatori di numeri casuali implementano, e questo trait deve essere nello scope affinché possiamo usare quei metodi. Il Capitolo 10 coprirà i trait in dettaglio.
Successivamente, aggiungiamo due righe nel mezzo. Nella prima riga, chiamiamo la funzione rand::thread_rng
che ci dà il particolare generatore di numeri casuali che useremo: uno che è locale al thread di esecuzione corrente ed è seminato dal sistema operativo. Poi chiamiamo il metodo gen_range
sul generatore di numeri casuali. Questo metodo è definito dal trait Rng
che abbiamo portato nello scope con l'istruzione use rand::Rng;
. Il metodo gen_range
prende un'espressione di intervallo come argomento e genera un numero casuale nell'intervallo. Il tipo di espressione di intervallo che stiamo usando qui prende la forma start..=end
ed è inclusivo sui limiti inferiori e superiori, quindi dobbiamo specificare 1..=100
per richiedere un numero tra 1 e 100.
Nota: Non saprai solo quali trait usare e quali metodi e funzioni chiamare da un crate, quindi ogni crate ha documentazione con istruzioni per usarlo. Un'altra caratteristica interessante di Cargo è che eseguendo il comando
cargo doc --open
verrà costruita la documentazione fornita da tutte le tue dipendenze localmente e aperta nel tuo browser. Se sei interessato ad altre funzionalità nel craterand
, per esempio, eseguicargo doc --open
e fai clic surand
nella barra laterale a sinistra.
La seconda nuova riga stampa il numero segreto. Questo è utile mentre stiamo sviluppando il programma per poterlo testare, ma lo cancelleremo dalla versione finale. Non è molto un gioco se il programma stampa la risposta non appena inizia!
Prova a eseguire il programma alcune volte:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 2.53s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 7
Please input your guess.
4
You guessed: 4
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running `target/debug/guessing_game`
Indovina il numero!
Il numero segreto è: 83
Per favore inserisci il tuo indovinello.
5
Hai indovinato: 5
Dovresti ottenere numeri casuali diversi, e dovrebbero essere tutti numeri tra 1 e 100. Ottimo lavoro!
Confrontare l'Indovinello con il Numero Segreto
Ora che abbiamo l'input dell'utente e un numero casuale, possiamo confrontarli. Questo passaggio è mostrato nel Listing 2-4. Nota che questo codice non compila ancora, come spiegheremo.
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
// --snip--
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
Per prima cosa aggiungiamo un'altra istruzione use
, portando un tipo chiamato
std::cmp::Ordering
nello scope dalla libreria standard. Il tipo Ordering
è un altro enum e ha le varianti Less
, Greater
, e Equal
. Questi sono i tre risultati possibili quando confronti due valori.
Poi aggiungiamo cinque nuove righe in fondo che utilizzano il tipo Ordering
. Il metodo cmp
confronta due valori e può essere chiamato su qualsiasi cosa possa essere confrontata. Prende un riferimento a ciò con cui vuoi confrontare: qui sta confrontando guess
con il secret_number
. Poi restituisce una variante dell'enum Ordering
che abbiamo portato nello scope con l'istruzione use
. Utilizziamo un'espressione match
per decidere cosa fare successivamente in base a quale variante di Ordering
è stata restituita dalla chiamata a cmp
con i valori in guess
e secret_number
.
Un'espressione match
è composta da braccia. Un braccio consiste in un pattern da abbinare e il codice che dovrebbe essere eseguito se il valore dato a match
si adatta a quel pattern del braccio. Rust prende il valore dato a match
e guarda attraverso il pattern di ciascun braccio a turno. I pattern e il costrutto match
sono potenti funzionalità di Rust: ti permettono di esprimere una varietà di situazioni che il tuo codice potrebbe incontrare e ti assicurano di gestirle tutte. Queste funzionalità saranno trattate in dettaglio nel Capitolo 6 e nel Capitolo 18, rispettivamente.
Esaminiamo un esempio con l'espressione match
che usiamo qui. Supponiamo che l'utente abbia indovinato 50 e il numero segreto generato casualmente questa volta sia 38.
Quando il codice confronta 50 con 38, il metodo cmp
restituirà
Ordering::Greater
perché 50 è maggiore di 38. L'espressione match
ottiene il valore Ordering::Greater
e inizia a controllare il pattern di ciascun braccio. Guarda il pattern del primo braccio, Ordering::Less
, e vede che il valore Ordering::Greater
non corrisponde a Ordering::Less
, quindi ignora il codice in quel braccio e passa al prossimo braccio. Il pattern del prossimo braccio è Ordering::Greater
, che corrisponde a Ordering::Greater
! Il codice associato in quel braccio verrà eseguito e stampa Too big!
sullo schermo. L'espressione match
termina dopo il primo abbinamento riuscito, quindi non guarderà l'ultimo braccio in questo scenario.
Tuttavia, il codice nel Listing 2-4 non compila ancora. Proviamo:
$ cargo build
Compiling libc v0.2.86
Compiling getrandom v0.2.2
Compiling cfg-if v1.0.0
Compiling ppv-lite86 v0.2.10
Compiling rand_core v0.6.2
Compiling rand_chacha v0.3.0
Compiling rand v0.8.5
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
error[E0308]: mismatched types
--> src/main.rs:22:21
|
22 | match guess.cmp(&secret_number) {
| --- ^^^^^^^^^^^^^^ expected struct `String`, found integer
| |
| arguments to this function are incorrect
|
= note: expected reference `&String`
found reference `&{integer}`
note: associated function defined here
--> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/cmp.rs:783:8
For more information about this error, try `rustc --explain E0308`.
error: could not compile `guessing_game` due to previous error
Il nucleo dell'errore afferma che ci sono tipi non corrispondenti. Rust ha un sistema di tipi forte e statico. Tuttavia, ha anche l'inferenza dei tipi. Quando abbiamo scritto let mut guess = String::new()
, Rust è stato in grado di inferire che guess
dovrebbe essere una String
e non ci ha fatto scrivere il tipo. Il secret_number
, d'altra parte, è un tipo numerico. Alcuni dei tipi numerici di Rust possono avere un valore tra 1 e 100: i32
, un numero a 32 bit; u32
, un numero senza segno a 32 bit; i64
, un numero a 64 bit; così come altri. Se non diversamente specificato, Rust predefinito è uno i32
, che è il tipo di secret_number
a meno che tu non aggiunga informazioni di tipo altrove che farebbero inferire a Rust un tipo numerico diverso. La ragione dell'errore è che Rust non può confrontare una stringa e un tipo numerico.
In definitiva, vogliamo convertire la String
che il programma legge come input in un tipo numerico in modo da poterla confrontare numericamente con il numero segreto. Lo facciamo aggiungendo questa riga al corpo della funzione main
:
Filename: src/main.rs
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
// --snip--
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
La riga è:
let guess: u32 = guess.trim().parse().expect("Please type a number!");
Creiamo una variabile chiamata guess
. Ma aspetta, il programma non ha già una variabile chiamata guess
? Sì, ma fortunatamente Rust ci permette di ombreggiare il valore precedente di guess
con uno nuovo. L'ombreggiatura ci permette di riutilizzare il nome della variabile guess
piuttosto che costringerci a creare due variabili uniche, come guess_str
e guess
, per esempio. Copriremo questo in maggior dettaglio nel Capitolo 3, ma per ora, sappi che questa funzionalità è spesso utilizzata quando vuoi convertire un valore da un tipo a un altro tipo.
Abbiamo associato questa nuova variabile all'espressione guess.trim().parse()
. Il guess
nell'espressione si riferisce alla variabile guess
originale che conteneva
l'input come una stringa. Il metodo trim
su un'istanza di String
eliminerà qualsiasi
spazio bianco all'inizio e alla fine, cosa che dobbiamo fare per poter confrontare la
stringa con il u32
, che può contenere solo dati numerici. L'utente deve premere
invio per soddisfare read_line
e inserire il proprio guess, il che aggiunge un
carattere di nuova linea alla stringa. Ad esempio, se l'utente digita 5 e
preme invio, guess
apparirà così: 5\n
. Il \n
rappresenta
"nuova linea". (Su Windows, premendo invio si genera un ritorno a capo
e una nuova linea, \r\n
.) Il metodo trim
elimina \n
o \r\n
, risultando
in solo 5
.
Il metodo parse
sulle stringhe converte una stringa in
un altro tipo. Qui, lo usiamo per convertire da una stringa a un numero. Dobbiamo
dire a Rust il tipo di numero esatto che vogliamo usando let guess: u32
. I due punti
(:
) dopo guess
indicano a Rust che annoteremo il tipo della variabile. Rust ha diversi
tipi di numeri integrati; il u32
visto qui è un intero senza segno a 32 bit.
È una buona scelta predefinita per un numero positivo piccolo. Imparerai altri
tipi di numeri nel Capitolo 3.
Inoltre, l'annotazione u32
in questo programma di esempio e il confronto
con secret_number
implica che Rust dedurrà che secret_number
dovrebbe essere
un u32
anche. Quindi ora il confronto sarà tra due valori dello stesso
tipo!
Il metodo parse
funzionerà solo su caratteri che possono essere logicamente convertiti
in numeri e quindi può facilmente causare errori. Se, per esempio, la stringa
conteneva A👍%
, non ci sarebbe modo di convertire ciò in un numero. Poiché potrebbe
fallire, il metodo parse
restituisce un tipo Result
, proprio come il metodo read_line
(discusso in precedenza in “Gestire i Potenziali Errori con Result
”). Tratteremo
questo Result
allo stesso modo usando nuovamente il metodo expect
. Se parse
restituisce una variante Err
del Result
perché non è riuscita a creare un numero dalla
stringa, la chiamata expect
farà crollare il gioco e stampare il messaggio che gli diamo.
Se parse
riesce a convertire correttamente la stringa in un numero, restituirà la
variante Ok
del Result
, e expect
restituirà il numero che vogliamo dal
valore Ok
.
Eseguiamo ora il programma:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 58
Please input your guess.
76
You guessed: 76
Too big!
Fantastico! Anche se sono stati aggiunti spazi prima del guess, il programma ha comunque capito che l'utente ha guessato 76. Esegui il programma alcune volte per verificare il diverso comportamento con diversi tipi di input: indovinare il numero correttamente, indovinare un numero troppo alto e indovinare un numero troppo basso.
Abbiamo la maggior parte del gioco che funziona ora, ma l'utente può fare solo un guess. Cambiamo ciò aggiungendo un loop!
Consentire Molteplici Guess con il Looping
La parola chiave loop
crea un loop infinito. Aggiungeremo un loop per dare agli utenti
più possibilità di indovinare il numero:
Filename: src/main.rs
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
// --snip--
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
// --snip--
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
}
Come puoi vedere, abbiamo spostato tutto dall'invito a inserire il guess in avanti all'interno di un loop. Assicurati di indentare le righe all'interno del loop di altri quattro spazi ciascuna e esegui di nuovo il programma. Il programma ora chiederà un altro guess per sempre, il che in realtà introduce un nuovo problema. Sembra che l'utente non possa smettere!
L'utente potrebbe sempre interrompere il programma utilizzando la scorciatoia da tastiera
ctrl-c. Ma c'è un altro modo per sfuggire a questo mostro insaziabile,
come menzionato nella discussione sul parse
in “Confrontare il Guess con il
Numero Segreto”: se
l'utente inserisce una risposta non numerica, il programma si bloccherà. Possiamo sfruttare
ciò per permettere all'utente di uscire, come mostrato qui:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 59
Please input your guess.
45
You guessed: 45
Too small!
Please input your guess.
60
You guessed: 60
Too big!
Please input your guess.
59
You guessed: 59
You win!
Please input your guess.
quit
thread 'main' panicked at 'Please type a number!: ParseIntError { kind: InvalidDigit }', src/main.rs:28:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Digitare quit
uscirà dal gioco, ma come noterai, così farà anche l'inserimento di qualsiasi
altro input non numerico. Questo è subottimale, per non dire altro; vogliamo che il gioco
si fermi anche quando il numero corretto è indovinato.
Uscire Dopo un Indovinare Corretto
Programmiamo il gioco per uscire quando l'utente vince aggiungendo un'istruzione break
:
Filename: src/main.rs
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
// --snip--
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
Aggiungere la riga break
dopo You win!
fa uscire il programma dal loop quando
l'utente indovina correttamente il numero segreto. Uscire dal loop significa anche
uscire dal programma, poiché il loop è l'ultima parte di main
.
Gestire l'Input Non Valido
Per perfezionare ulteriormente il comportamento del gioco, invece di far crollare il programma quando
l'utente inserisce un input non numerico, facciamo in modo che il gioco ignori l'input non numerico in modo
che l'utente possa continuare a indovinare. Possiamo farlo modificando la riga in cui guess
viene convertito da una String
a un u32
, come mostrato nel Listing 2-5.
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
// --snip--
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
// --snip--
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
Passiamo da una chiamata expect
a un'espressione match
per passare dall'usare un crash
per un errore a gestire l'errore. Ricorda che parse
restituisce un tipo Result
e Result
è un enum che ha le varianti Ok
e Err
. Qui usiamo un'espressione match
, come abbiamo fatto con il risultato Ordering
del metodo cmp
.
Se parse
è in grado di trasformare con successo la stringa in un numero, restituirà
un valore Ok
che contiene il numero risultante. Quel valore Ok
corrisponderà al pattern
del primo braccio, e l'espressione match
restituirà semplicemente il valore num
che parse
ha prodotto e messo all'interno del valore Ok
. Quel numero finirà esattamente dove lo
vogliamo nella nuova variabile guess
che stiamo creando.
Se parse
non è in grado di trasformare la stringa in un numero, restituirà un
valore Err
che contiene ulteriori informazioni sull'errore. Il valore Err
non corrisponde al pattern Ok(num)
nel primo braccio del match
, ma corrisponde
al pattern Err(_)
nel secondo braccio. Il trattino basso, _
, è un
valore jolly; in questo esempio, stiamo dicendo che vogliamo abbinare tutti i valori Err
,
indipendentemente dalle informazioni che hanno dentro. Quindi il programma eseguirà il codice
del secondo braccio, continue
, che dice al programma di andare alla
prossima iterazione del loop
e chiedere un altro guess. Quindi, effettivamente, il
programma ignora tutti gli errori che parse
potrebbe incontrare!
Ora tutto nel programma dovrebbe funzionare come previsto. Proviamolo:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 4.45s
Running `target/debug/guessing_game`
Guess the number!
The secret number is: 61
Please input your guess.
10
You guessed: 10
Too small!
Please input your guess.
99
You guessed: 99
Too big!
Please input your guess.
foo
Please input your guess.
61
You guessed: 61
You win!
Fantastico! Con un piccolo ritocco finale, completeremo il gioco di indovina. Richiama
che il programma sta ancora stampando il numero segreto. Funzionava bene per
i test, ma rovina il gioco. Cancelliamo il println!
che produce il
numero segreto. Il Listing 2-6 mostra il codice finale.
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
A questo punto, hai costruito con successo il gioco di indovina. Congratulazioni!
Sommario
Questo progetto è stato un modo pratico per introdurti a molti nuovi concetti
di Rust: let
, match
, funzioni, l'uso di crate esterni, e altro. Nei próximos
due capitoli, imparerai questi concetti in modo più dettagliato. Il Capitolo 3
copre concetti che la maggior parte dei linguaggi di programmazione hanno, come variabili, tipi
di dati e funzioni, e mostra come usarli in Rust. Il Capitolo 4 esplora
la proprietà, una caratteristica che rende Rust diverso dagli altri linguaggi. Il Capitolo 5
discute gli struct e la sintassi dei metodi, e il Capitolo 6 spiega come funzionano
gli enum.
Concetti di Programmazione Comuni
Questo capitolo copre concetti che appaiono in quasi ogni linguaggio di programmazione e come funzionano in Rust. Molti linguaggi di programmazione hanno molto in comune al loro interno. Nessuno dei concetti presentati in questo capitolo è unico a Rust, ma li discuteremo nel contesto di Rust e spiegheremo le convenzioni riguardanti l'uso di questi concetti.
In particolare, imparerai riguardo le variabili, i tipi di base, le funzioni, i commenti e il controllo del flusso. Queste fondamenta saranno in ogni programma Rust, e impararle presto ti darà una forte base da cui partire.
Parole Chiave
Il linguaggio Rust ha un insieme di parole chiave che sono riservate per l'uso esclusivo da parte del linguaggio, proprio come in altri linguaggi. Tieni presente che non puoi usare queste parole come nomi di variabili o funzioni. La maggior parte delle parole chiave ha significati speciali e le userai per eseguire vari compiti nei tuoi programmi Rust; alcune non hanno attualmente funzionalità associate, ma sono state riservate per funzionalità che potrebbero essere aggiunte a Rust in futuro. Puoi trovare una lista delle parole chiave in Appendice A.
Variabili e Mutabilità
Come menzionato nella sezione “Storing Values with Variables”, per impostazione predefinita, le variabili sono immutabili. Questo è uno dei tanti suggerimenti che Rust ti offre per scrivere il tuo codice in un modo che sfrutta la sicurezza e la facile concorrenza che Rust offre. Tuttavia, hai comunque l'opzione di rendere le tue variabili mutabili. Esploriamo come e perché Rust ti incoraggia a favorire l'immutabilità e perché a volte potresti voler rinunciare a questa caratteristica.
Quando una variabile è immutabile, una volta che un valore è assegnato a un nome, non puoi cambiare
quel valore. Per illustrarlo, genera un nuovo progetto chiamato variables nella tua directory projects usando cargo new variables
.
Poi, nella tua nuova directory variables, apri src/main.rs e sostituisci il suo codice con il seguente codice, che non compilerà ancora:
Filename: src/main.rs
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
Salva ed esegui il programma usando cargo run
. Dovresti ricevere un messaggio di errore
riguardante un errore di immutabilità, come mostrato in questo output:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
3 | println!("The value of x is: {x}");
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
error: could not compile `variables` due to previous error
Questo esempio mostra come il compilatore ti aiuta a trovare errori nei tuoi programmi. Gli errori del compilatore possono essere frustranti, ma in realtà significano solo che il tuo programma ancora non sta facendo in modo sicuro ciò che vuoi che faccia; non significano affatto che tu non sia un bravo programmatore! Anche i Rustaceans esperti ricevono errori dal compilatore.
Hai ricevuto il messaggio di errore cannot assign twice to immutable variable `x`
perché hai cercato di assegnare un secondo valore alla variabile x
immutabile.
È importante che riceviamo errori di compilazione quando tentiamo di cambiare un valore designato come immutabile perché questa stessa situazione può portare a bug. Se una parte del nostro codice opera sull'assunto che un valore non cambierà mai e un'altra parte del nostro codice cambia quel valore, è possibile che la prima parte del codice non faccia ciò per cui è stata progettata. La causa di questo tipo di bug può essere difficile da rintracciare retroattivamente, specialmente quando la seconda parte di codice cambia il valore solo a volte. Il compilatore di Rust garantisce che quando dichiari che un valore non cambierà, non cambierà davvero, così non devi tenerne traccia da solo. Il tuo codice è quindi più facile da ragionare.
Ma la mutabilità può essere molto utile e può rendere il codice più conveniente da scrivere.
Anche se le variabili sono immutabili per impostazione predefinita, puoi renderle mutabili aggiungendo mut
davanti al nome della variabile come hai fatto nel Capitolo
2. Aggiungere mut
trasmette anche
intenzione ai futuri lettori del codice, indicando che altre parti del codice
cambieranno il valore di questa variabile.
Per esempio, cambiamo src/main.rs come segue:
Filename: src/main.rs
fn main() { let mut x = 5; println!("The value of x is: {x}"); x = 6; println!("The value of x is: {x}"); }
Quando eseguiamo il programma ora, otteniamo questo:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
Ci è permesso cambiare il valore assegnato a x
da 5
a 6
quando mut
è
usato. In definitiva, decidere se usare la mutabilità o meno spetta a te e
dipende da ciò che ritieni sia più chiaro in quella particolare situazione.
Costanti
Come le variabili immutabili, le costanti sono valori che sono assegnati a un nome e non possono essere cambiati, ma ci sono alcune differenze tra costanti e variabili.
Prima di tutto, non è permesso usare mut
con le costanti. Le costanti non sono solo
immutabili per impostazione predefinita—sono sempre immutabili. Dichiari le costanti usando la
parola chiave const
invece della parola chiave let
, e il tipo del valore deve
essere annotato. Tratteremo tipi e annotazioni dei tipi nella prossima sezione,
“Data Types”, quindi non preoccuparti dei dettagli
adesso. Sappi solo che devi sempre annotare il tipo.
Le costanti possono essere dichiarate in qualsiasi ambito, incluso l'ambito globale, il che le rende utili per valori che molte parti del codice devono conoscere.
L'ultima differenza è che le costanti possono essere impostate solo su un'espressione costante, non sul risultato di un valore che potrebbe essere computato solo a runtime.
Ecco un esempio di dichiarazione di una costante:
#![allow(unused)] fn main() { const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3; }
Il nome della costante è THREE_HOURS_IN_SECONDS
e il suo valore è impostato sul
risultato della moltiplicazione di 60 (il numero di secondi in un minuto) per 60 (il numero
di minuti in un'ora) per 3 (il numero di ore che vogliamo contare in questo
programma). La convenzione di denominazione di Rust per le costanti è usare tutte le lettere maiuscole con
trattini bassi tra le parole. Il compilatore è in grado di valutare un set limitato di
operazioni a tempo di compilazione, il che ci consente di scegliere di scrivere questo valore in un modo che sia più facile da capire e verificare, piuttosto che impostare questa costante
al valore 10,800. Consulta la sezione del Riferimento Rust sull'evaluazione delle costanti per ulteriori informazioni sulle operazioni che
possono essere utilizzate quando si dichiarano le costanti.
Le costanti sono valide per tutto il tempo in cui un programma è in esecuzione, all'interno dell'ambito in cui sono state dichiarate. Questa proprietà rende le costanti utili per valori nel tuo dominio applicativo di cui più parti del programma potrebbero aver bisogno, come il numero massimo di punti che qualsiasi giocatore di un gioco è autorizzato a guadagnare, o la velocità della luce.
Denominare i valori hardcoded usati in tutto il tuo programma come costanti è utile per trasmettere il significato di quel valore ai futuri manutentori del codice. Inoltre, aiuta ad avere un solo posto nel tuo codice che avresti bisogno di cambiare se il valore hardcoded dovesse essere aggiornato in futuro.
Shadowing
Come hai visto nel tutorial del gioco di indovinare nel Capitolo
2, puoi dichiarare una
nuova variabile con lo stesso nome di una variabile precedente. I Rustaceans dicono che la
prima variabile è shadowed dalla seconda, il che significa che la seconda
variabile è ciò che il compilatore vedrà quando usi il nome della variabile.
In effetti, la seconda variabile offusca la prima, andando a sostituire ogni uso del
nome della variabile finché non viene essa stessa offuscata o l'ambito termina.
Possiamo eseguire un’operazione di shadowing su una variabile usando lo stesso nome della variabile e ripetendo l'uso della parola chiave let
come segue:
Filename: src/main.rs
fn main() { let x = 5; let x = x + 1; { let x = x * 2; println!("The value of x in the inner scope is: {x}"); } println!("The value of x is: {x}"); }
Questo programma prima assegna x
ad un valore di 5
. Poi crea una nuova variabile
x
ripetendo let x =
, prendendo il valore originale e aggiungendo 1
quindi
il valore di x
diventa 6
. Poi, all'interno di un ambito interno creato con
le parentesi graffe, la terza dichiarazione let
sovrasta anche x
e crea una nuova
variabile, moltiplicando il valore precedente per 2
per assegnare a x
un valore di
12
. Quando quell'ambito finisce, il shadowing interno termina e x
torna ad essere 6
.
Quando eseguiamo questo programma, produrrà il seguente output:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6
Lo shadowing è diverso dal marcare una variabile come mut
perché otterremo un
errore a tempo di compilazione se accidentalmente tentiamo di riassegnare a questa variabile senza
usare la parola chiave let
. Usando let
, possiamo effettuare alcune trasformazioni
su un valore ma far sì che la variabile sia immutabile dopo che tali trasformazioni
sono state completate.
L'altra differenza tra mut
e shadowing è che, visto che stiamo
effettivamente creando una nuova variabile quando utilizziamo nuovamente la parola chiave let
, possiamo
cambiare il tipo del valore ma riutilizzare lo stesso nome. Per esempio, supponiamo
che il nostro programma chieda a un utente di mostrare quante spaziature desidera tra un po' di testo
immettendo spazi, e poi vogliamo memorizzare quell'input come un numero:
fn main() { let spaces = " "; let spaces = spaces.len(); }
La prima variabile spaces
è di tipo stringa e la seconda variabile spaces
è di tipo
numerico. Lo shadowing ci risparmia quindi dal dover inventare
nomi diversi, come spaces_str
e spaces_num
; invece, possiamo riutilizzare
il più semplice nome spaces
. Tuttavia, se proviamo a usare mut
per questo, come mostrato
qui, otterremo un errore a tempo di compilazione:
fn main() {
let mut spaces = " ";
spaces = spaces.len();
}
L'errore dice che non ci è permesso di mutare il tipo di una variabile:
$ cargo run
Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
--> src/main.rs:3:14
|
2 | let mut spaces = " ";
| ----- expected due to this value
3 | spaces = spaces.len();
| ^^^^^^^^^^^^ expected `&str`, found `usize`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` due to previous error
Ora che abbiamo esplorato come funzionano le variabili, diamo un'occhiata a più tipi di dati che possono avere.
Tipi di Dati
Ogni valore in Rust appartiene a un certo tipo di dato, il che indica a Rust che tipo di dati sono specificati in modo che sappia come lavorare con quei dati. Esamineremo due sottoinsiemi di tipi di dati: scalari e composti.
Tieni presente che Rust è un linguaggio tipizzato staticamente, il che significa che deve conoscere i tipi di tutte le variabili durante la compilazione. Di solito, il compilatore può inferire quale tipo vogliamo utilizzare in base al valore e a come lo utilizziamo. Nei casi in cui sono possibili molti tipi, come quando abbiamo convertito una String
in un tipo numerico utilizzando parse
nella sezione "Confronto del Presupposto con il Numero Segreto" nel Capitolo 2, dobbiamo aggiungere un'annotazione del tipo, come questa:
#![allow(unused)] fn main() { let guess: u32 = "42".parse().expect("Non è un numero!"); }
Se non aggiungiamo l'annotazione del tipo : u32
mostrata nel codice precedente, Rust visualizzerà il seguente errore, il che significa che il compilatore ha bisogno di ulteriori informazioni da noi per capire quale tipo vogliamo utilizzare:
$ cargo build
Compiling no_type_annotations v0.1.0 (file:///projects/no_type_annotations)
error[E0282]: type annotations needed
--> src/main.rs:2:9
|
2 | let guess = "42".parse().expect("Not a number!");
| ^^^^^
|
help: consider giving `guess` an explicit type
|
2 | let guess: _ = "42".parse().expect("Not a number!");
| +++
For more information about this error, try `rustc --explain E0282`.
error: could not compile `no_type_annotations` due to previous error
Vedrai annotazioni di tipo diverse per altri tipi di dati.
Tipi Scalari
Un tipo scalare rappresenta un singolo valore. Rust ha quattro tipi scalari principali: interi, numeri a virgola mobile, booleani e caratteri. Potresti riconoscerli da altri linguaggi di programmazione. Vediamo come funzionano in Rust.
Tipi Interi
Un intero è un numero senza componente frazionaria. Abbiamo utilizzato un tipo intero nel Capitolo 2, il tipo u32
. Questa dichiarazione di tipo indica che il valore associato deve essere un intero senza segno (i tipi interi con segno iniziano con i
invece di u
) che occupa 32 bit di spazio. La Tabella 3-1 mostra i tipi di interi integrati in Rust. Possiamo utilizzare qualsiasi di queste varianti per dichiarare il tipo di un valore intero.
Lunghezza | Con Segno | Senza Segno |
---|---|---|
8-bit | i8 | u8 |
16-bit | i16 | u16 |
32-bit | i32 | u32 |
64-bit | i64 | u64 |
128-bit | i128 | u128 |
arch | isize | usize |
Ogni variante può essere con segno o senza segno e ha una dimensione esplicita. Con segno e senza segno si riferiscono alla possibilità che il numero sia negativo, in altre parole, se il numero deve avere un segno associato (con segno) o se sarà sempre positivo e può quindi essere rappresentato senza un segno (senza segno). È come scrivere numeri su carta: quando il segno è importante, un numero viene mostrato con un segno positivo o negativo; tuttavia, quando è sicuro presumere che il numero sia positivo, viene mostrato senza segno. I numeri con segno sono memorizzati utilizzando la rappresentazione complemento a due.
Ogni variante con segno può memorizzare numeri da -(2n - 1) a 2n - 1 - 1 inclusi, dove n è il numero di bit che quella variante utilizza. Quindi un i8
può memorizzare numeri da -(27) a 27 - 1, che equivale a -128 a 127. Le varianti senza segno possono memorizzare numeri da 0 a 2n - 1, quindi un u8
può memorizzare numeri da 0 a 28 - 1, che equivale a 0 a 255.
Inoltre, i tipi isize
e usize
dipendono dall'architettura del computer su cui è in esecuzione il programma, che è indicata nella tabella come "arch": 64 bit se si è su un'architettura a 64 bit e 32 bit se si è su un'architettura a 32 bit.
Puoi scrivere letterali interi in una qualsiasi delle forme mostrate nella Tabella 3-2. Nota che i letterali numerici che possono essere di più tipi numerici consentono un suffisso di tipo, come 57u8
, per designare il tipo. I letterali numerici possono anche utilizzare _
come separatore visivo per rendere il numero più facile da leggere, come 1_000
, che avrà lo stesso valore come se avessi specificato 1000
.
Letterali Numerici | Esempio |
---|---|
Decimale | 98_222 |
Esadecimale | 0xff |
Ottale | 0o77 |
Binario | 0b1111_0000 |
Byte (u8 only) | b'A' |
Quindi, come sapere quale tipo di intero utilizzare? Se non sei sicuro, i predefiniti di Rust sono generalmente buoni punti di partenza: i tipi interi predefiniti sono i32
.
La situazione principale in cui utilizzeresti isize
o usize
è quando si indicizza una sorta di collezione.
Overflow degli Interi
Supponiamo di avere una variabile di tipo
u8
che può contenere valori tra 0 e 255. Se provi a cambiare la variabile a un valore al di fuori di quel range, come 256, si verificherà un overflow degli interi, il che può portare a uno dei due comportamenti. Quando compili in modalità debug, Rust include controlli per l'overflow degli interi che causano il panic del programma a runtime se si verifica questo comportamento. Rust usa il termine panico quando un programma termina con un errore; discuteremo dei panici in dettaglio nella sezione "Errori irrecuperabili conpanic!
" del Capitolo 9.Quando compili in modalità release con il flag
--release
, Rust non include controlli per l'overflow degli interi che causano panici. Invece, se si verifica un overflow, Rust esegue il wrapping complementare a due. In breve, i valori superiori al massimo valore che il tipo può contenere "avvolgono" al minimo dei valori che il tipo può contenere. Nel caso di unu8
, il valore 256 diventa 0, il valore 257 diventa 1, e così via. Il programma non andrà in panico, ma la variabile avrà un valore che probabilmente non è quello che ti aspettavi di avere. Fare affidamento sul comportamento di wrapping per l'overflow degli interi è considerato un errore.Per gestire esplicitamente la possibilità di overflow, puoi utilizzare queste famiglie di metodi forniti dalla libreria standard per i tipi numerici primitivi:
- Wrapping in tutte le modalità con i metodi
wrapping_*
, comewrapping_add
.- Restituire il valore
None
se si verifica overflow con i metodichecked_*
.- Restituire il valore e un booleano che indica se si è verificato overflow con i metodi
overflowing_*
.- Saturare ai valori minimo o massimo con i metodi
saturating_*
.
Tipi a Virgola Mobile
Rust ha anche due tipi primitivi per i numeri a virgola mobile, che sono numeri con punti decimali. I tipi a virgola mobile di Rust sono f32
e f64
, che sono rispettivamente di 32 bit e 64 bit. Il tipo predefinito è f64
perché sui moderni CPU è approssimativamente della stessa velocità di f32
ma è capace di maggiore precisione. Tutti i tipi a virgola mobile sono con segno.
Ecco un esempio che mostra i numeri a virgola mobile in azione:
Nome del file: src/main.rs
fn main() { let x = 2.0; // f64 let y: f32 = 3.0; // f32 }
I numeri a virgola mobile sono rappresentati secondo lo standard IEEE-754. Il tipo f32
è un float a precisione singola, e f64
ha doppia precisione.
Operazioni Numeriche
Rust supporta le operazioni matematiche di base che ci si aspetta per tutti i tipi di numero: addizione, sottrazione, moltiplicazione, divisione e resto. La divisione intera tronca verso zero al numero intero più vicino. Il codice seguente mostra come utilizzeresti ciascuna operazione numerica in un'istruzione let
:
Nome del file: src/main.rs
fn main() { // addition let sum = 5 + 10; // subtraction let difference = 95.5 - 4.3; // multiplication let product = 4 * 30; // division let quotient = 56.7 / 32.2; let truncated = -5 / 3; // Results in -1 // remainder let remainder = 43 % 5; }
Ogni espressione in queste istruzioni utilizza un operatore matematico e valuta un singolo valore, che viene quindi associato a una variabile. Appendice B contiene un elenco di tutti gli operatori forniti da Rust.
Il Tipo Booleano
Come nella maggior parte degli altri linguaggi di programmazione, un tipo booleano in Rust ha due possibili valori: true
e false
. I booleani sono di un byte. Il tipo booleano in Rust è specificato usando bool
. Per esempio:
Nome del file: src/main.rs
fn main() { let t = true; let f: bool = false; // with explicit type annotation }
Il modo principale per usare i valori booleani è tramite le espressioni condizionali, come un'espressione if
. Copriremo come funzionano le espressioni if
in Rust nella sezione "Controllo del Flusso".
Il Tipo Carattere
Il tipo char
di Rust è il tipo alfabetico più primitivo del linguaggio. Ecco alcuni esempi di dichiarazione di valori char
:
Nome del file: src/main.rs
fn main() { let c = 'z'; let z: char = 'ℤ'; // with explicit type annotation let heart_eyed_cat = '😻'; }
Nota che specifichiamo i letterali char
con virgolette singole, a differenza dei letterali stringa, che usano virgolette doppie. Il tipo char
di Rust è di quattro byte e rappresenta un valore scalare Unicode, il che significa che può rappresentare molto più del semplice ASCII. Lettere accentate; caratteri cinesi, giapponesi e coreani; emoji; e spazi a larghezza zero sono tutti valori char
validi in Rust. I valori scalari Unicode vanno da U+0000
a U+D7FF
e da U+E000
a U+10FFFF
inclusi. Tuttavia, un “carattere” non è realmente un concetto in Unicode, quindi la tua intuizione umana su cosa sia un “carattere” potrebbe non corrispondere a ciò che un char
è in Rust. Discuteremo di questo argomento in dettaglio in "Memorizzazione del Testo Codificato UTF-8 con Stringhe" nel Capitolo 8.
Tipi Composti
I tipi composti possono raggruppare più valori in un unico tipo. Rust ha due tipi composti primitivi: tuple e array.
Il Tipo Tuple
Una tupla è un modo generale per raggruppare un numero di valori con una varietà di tipi in un unico tipo composto. Le tuple hanno una lunghezza fissa: una volta dichiarate, non possono crescere o diminuire in dimensioni.
Creiamo una tupla scrivendo un elenco di valori separati da virgole all'interno di parentesi. Ogni posizione nella tupla ha un tipo, e i tipi dei diversi valori nella tupla non devono essere uguali. Abbiamo aggiunto delle annotazioni di tipo facoltative in questo esempio:
Nome del file: src/main.rs
fn main() { let tup: (i32, f64, u8) = (500, 6.4, 1); }
La variabile tup
si associa all'intera tupla perché una tupla è considerata un singolo elemento composto. Per ottenere i singoli valori di una tupla, possiamo utilizzare il pattern matching per destrutturare un valore tupla, come questo:
Nome del file: src/main.rs
fn main() { let tup = (500, 6.4, 1); let (x, y, z) = tup; println!("The value of y is: {y}"); }
Questo programma crea prima una tupla e la associa alla variabile tup
. Utilizza quindi un modello con let
per prendere tup
e trasformarla in tre variabili separate, x
, y
e z
. Questo è chiamato destrutturazione perché scompone la singola tupla in tre parti. Infine, il programma stampa il valore di y
, che è 6.4
.
Possiamo anche accedere a un elemento di una tupla direttamente utilizzando un punto (.
) seguito dall'indice del valore a cui vogliamo accedere. Per esempio:
Nome del file: src/main.rs
fn main() { let x: (i32, f64, u8) = (500, 6.4, 1); let five_hundred = x.0; let six_point_four = x.1; let one = x.2; }
Questo programma crea la tupla x
e poi accede a ciascun elemento della tupla utilizzando i loro rispettivi indici. Come nella maggior parte dei linguaggi di programmazione, il primo indice in una tupla è 0.
La tupla senza alcun valore ha un nome speciale, unità. Questo valore e il suo tipo corrispondente sono entrambi scritti ()
e rappresentano un valore vuoto o un tipo di ritorno vuoto. Le espressioni restituiscono implicitamente il valore unità se non restituiscono alcun altro valore.
Il Tipo Array
Un altro modo per avere una raccolta di più valori è con un array. A differenza di una tupla, ogni elemento di un array deve avere lo stesso tipo. A differenza degli array in alcuni altri linguaggi, gli array in Rust hanno una lunghezza fissa.
Scriviamo i valori in un array come un elenco separato da virgole all'interno di parentesi quadre:
Nome del file: src/main.rs
fn main() { let a = [1, 2, 3, 4, 5]; }
Gli array sono utili quando vuoi che i tuoi dati siano allocati nello stack piuttosto che nello heap (discuteremo dello stack e dello heap più nel dettaglio nel Capitolo 4) o quando vuoi assicurarti di avere sempre un numero fisso di elementi. Un array non è flessibile come il tipo vettore, però. Un vettore è un tipo di raccolta simile fornito dalla libreria standard che è consentito crescere o ridursi in dimensioni. Se non sei sicuro se utilizzare un array o un vettore, è probabile che dovresti usare un vettore. Capitolo 8 tratta i vettori più in dettaglio.
Tuttavia, gli array sono più utili quando sai che il numero di elementi non dovrà cambiare. Ad esempio, se stavi usando i nomi dei mesi in un programma, probabilmente useresti un array anziché un vettore perché sai che conterrà sempre 12 elementi:
#![allow(unused)] fn main() { let months = ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"]; }
Scrivi il tipo di un array utilizzando le parentesi quadre con il tipo di ogni elemento, un punto e virgola, e quindi il numero di elementi nell'array, in questo modo:
#![allow(unused)] fn main() { let a: [i32; 5] = [1, 2, 3, 4, 5]; }
Qui, i32
è il tipo di ogni elemento. Dopo il punto e virgola, il numero 5
indica che l'array contiene cinque elementi.
Puoi anche inizializzare un array per contenere lo stesso valore per ciascun elemento specificando il valore iniziale, seguito da un punto e virgola, e poi la lunghezza dell'array tra parentesi quadre, come mostrato qui:
#![allow(unused)] fn main() { let a = [3; 5]; }
L'array chiamato a
conterrà 5
elementi che saranno inizialmente impostati al valore 3
. Questo è lo stesso che scrivere let a = [3, 3, 3, 3, 3];
ma in modo più conciso.
Accesso agli Elementi dell'Array
Un array è un singolo blocco di memoria di dimensioni note e fisse che può essere allocato nello stack. Puoi accedere agli elementi di un array utilizzando l'indicizzazione, come questo:
Nome del file: src/main.rs
fn main() { let a = [1, 2, 3, 4, 5]; let first = a[0]; let second = a[1]; }
In questo esempio, la variabile chiamata first
otterrà il valore 1
perché quello è il valore all'indice [0]
nell'array. La variabile chiamata second
otterrà il valore 2
dall'indice [1]
nell'array.
Accesso Non Valido agli Elementi dell'Array
Vediamo cosa succede se provi ad accedere a un elemento di un array che è oltre la fine dell'array. Diciamo che esegui questo codice, simile al gioco di indovinelli nel Capitolo 2, per ottenere un indice di un array dall'utente:
Nome del file: src/main.rs
use std::io;
fn main() {
let a = [1, 2, 3, 4, 5];
println!("Please enter an array index.");
let mut index = String::new();
io::stdin()
.read_line(&mut index)
.expect("Failed to read line");
let index: usize = index
.trim()
.parse()
.expect("Index entered was not a number");
let element = a[index];
println!("The value of the element at index {index} is: {element}");
}
Questo codice viene compilato correttamente. Se esegui questo codice utilizzando `cargo run` e inserisci `0`, `1`, `2`, `3` o `4`, il programma stamperà il valore corrispondente a quell'indice nell'array. Se invece inserisci un numero oltre la fine dell'array, come `10`, vedrai un output simile a questo:
<!-- manual-regeneration
cd listings/ch03-common-programming-concepts/no-listing-15-invalid-array-access
cargo run
10
-->
```console
thread 'main' panicked at src/main.rs:19:19:
index out of bounds: the len is 5 but the index is 10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Il programma ha causato un errore di runtime nel momento in cui si è utilizzato un valore non valido nell'operazione di indicizzazione. Il programma è terminato con un messaggio di errore e non ha eseguito l'istruzione finale println!
. Quando tenti di accedere a un elemento utilizzando l'indicizzazione, Rust controllerà che l'indice specificato sia inferiore alla lunghezza dell'array. Se l'indice è maggiore o uguale alla lunghezza, Rust entrerà in panico. Questo controllo deve avvenire a runtime, specialmente in questo caso, poiché il compilatore non può sapere quale valore l'utente inserirà quando eseguirà il codice successivamente.
Questo è un esempio dei principi di sicurezza della memoria di Rust in azione. In molti linguaggi di basso livello, questo tipo di controllo non viene eseguito, e quando si fornisce un indice errato, è possibile accedere a memoria non valida. Rust ti protegge da questo tipo di errore uscendo immediatamente invece di consentire l'accesso alla memoria e continuare. Il Capitolo 9 discute ulteriormente la gestione degli errori in Rust e come è possibile scrivere codice leggibile e sicuro che non vada in panico né permetta l'accesso a memoria non valida.
Funzioni
Le funzioni sono prevalenti nel codice Rust. Hai già visto una delle funzioni più importanti del linguaggio: la funzione main
, che è il punto di ingresso di molti programmi. Hai anche visto la parola chiave fn
, che ti permette di dichiarare nuove funzioni.
Il codice Rust utilizza lo snake case come convenzione per i nomi delle funzioni e delle variabili, in cui tutte le lettere sono minuscole e gli underscore separano le parole. Ecco un programma che contiene un esempio di definizione di funzione:
Nome del file: src/main.rs
fn main() { println!("Hello, world!"); another_function(); } fn another_function() { println!("Another function."); }
Definiamo una funzione in Rust inserendo fn
seguito dal nome della funzione e un insieme di parentesi. Le parentesi graffe indicano al compilatore dove inizia e termina il corpo della funzione.
Possiamo chiamare qualsiasi funzione che abbiamo definito inserendo il suo nome seguito da un insieme di parentesi. Poiché another_function
è definita nel programma, può essere chiamata dall'interno della funzione main
. Nota che abbiamo definito another_function
dopo la funzione main
nel codice sorgente; avremmo potuto definirla anche prima. A Rust non importa dove definisci le tue funzioni, solo che siano definite da qualche parte in uno scope visibile dal chiamante.
Iniziamo un nuovo progetto binario chiamato functions per esplorare ulteriormente le funzioni. Posiziona l'esempio di another_function
in src/main.rs ed eseguine l'esecuzione. Dovresti vedere il seguente output:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished dev [unoptimized + debuginfo] target(s) in 0.28s
Running `target/debug/functions`
Hello, world!
Another function.
Le linee vengono eseguite nell'ordine in cui appaiono nella funzione main
. Prima viene stampato il messaggio “Hello, world!” e poi viene chiamata another_function
e viene stampato il suo messaggio.
Parametri
Possiamo definire funzioni che hanno parametri, che sono variabili speciali che fanno parte della firma di una funzione. Quando una funzione ha parametri, puoi fornire valori concreti per quei parametri. Tecnicamente, i valori concreti sono chiamati argomenti, ma in conversazioni informali, le persone tendono a usare le parole parametro e argomento in modo intercambiabile per indicare sia le variabili nella definizione di una funzione sia i valori concreti passati quando chiami una funzione.
In questa versione di another_function
aggiungiamo un parametro:
Nome del file: src/main.rs
fn main() { another_function(5); } fn another_function(x: i32) { println!("The value of x is: {x}"); }
Prova a eseguire questo programma; dovresti ottenere il seguente output:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished dev [unoptimized + debuginfo] target(s) in 1.21s
Running `target/debug/functions`
The value of x is: 5
La dichiarazione di another_function
ha un parametro chiamato x
. Il tipo di x
è specificato come i32
. Quando passiamo 5
a another_function
, la macro println!
inserisce 5
dove nella stringa di formato c'erano le parentesi graffe contenenti x
.
Nelle firme delle funzioni, devi dichiarare il tipo di ogni parametro. Questa è una scelta deliberata nel design di Rust: richiedere annotazioni di tipo nelle definizioni delle funzioni significa che il compilatore quasi non ha mai bisogno che le usi altrove nel codice per capire a quale tipo ti riferisci. Il compilatore è anche in grado di fornire messaggi di errore più utili se sa quali tipi la funzione si aspetta.
Quando si definiscono più parametri, separare le dichiarazioni dei parametri con virgole, come segue:
Nome del file: src/main.rs
fn main() { print_labeled_measurement(5, 'h'); } fn print_labeled_measurement(value: i32, unit_label: char) { println!("The measurement is: {value}{unit_label}"); }
Questo esempio crea una funzione chiamata print_labeled_measurement
con due parametri. Il primo parametro si chiama value
ed è un i32
. Il secondo si chiama unit_label
ed è di tipo char
. La funzione quindi stampa un testo che contiene sia il value
che l'unit_label
.
Proviamo a eseguire questo codice. Sostituisci il programma attualmente nel file src/main.rs del tuo progetto functions con l'esempio precedente ed eseguilo usando cargo run
:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/functions`
The measurement is: 5h
Poiché abbiamo chiamato la funzione con 5
come valore per value
e 'h'
come valore per unit_label
, l'output del programma contiene quei valori.
Istruzioni ed Espressioni
I corpi delle funzioni sono costituiti da una serie di istruzioni che terminano facoltativamente con un'espressione. Finora, le funzioni che abbiamo trattato non hanno incluso un'espressione finale, ma hai visto un'espressione come parte di un'istruzione. Poiché Rust è un linguaggio basato su espressioni, questa è una distinzione importante da comprendere. Altri linguaggi non hanno le stesse distinzioni, quindi esaminiamo cosa sono le istruzioni e le espressioni e come le loro differenze influenzano i corpi delle funzioni.
- Istruzioni sono istruzioni che eseguono un'azione e non restituiscono un valore.
- Espressioni valutano un valore risultante. Esaminiamo alcuni esempi.
Abbiamo già utilizzato istruzioni ed espressioni. Creare una variabile e assegnarle un valore con la parola chiave let
è un'istruzione. Nell'Elenco 3-1, let y = 6;
è un'istruzione.
fn main() { let y = 6; }
Le definizioni di funzioni sono anche istruzioni; l'intero esempio precedente è un'istruzione in sé. (Come vedremo sotto, chiamare una funzione non è un'istruzione.)
Le istruzioni non restituiscono valori. Pertanto, non puoi assegnare un'istruzione let
a un'altra variabile, come tenta di fare il seguente codice; otterrai un errore:
Nome del file: src/main.rs
fn main() {
let x = (let y = 6);
}
Quando esegui questo programma, l'errore che ottieni è simile al seguente:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error: expected expression, found `let` statement
--> src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^
error: expected expression, found statement (`let`)
--> src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^^^^^^^
|
= note: variable declaration using `let` is a statement
error[E0658]: `let` expressions in this position are unstable
--> src/main.rs:2:14
|
2 | let x = (let y = 6);
| ^^^^^^^^^
|
= note: see issue #53667 <https://github.com/rust-lang/rust/issues/53667> for more information
warning: unnecessary parentheses around assigned value
--> src/main.rs:2:13
|
2 | let x = (let y = 6);
| ^ ^
|
= note: `#[warn(unused_parens)]` on by default
help: remove these parentheses
|
2 - let x = (let y = 6);
2 + let x = let y = 6;
|
For more information about this error, try `rustc --explain E0658`.
warning: `functions` (bin "functions") generated 1 warning
error: could not compile `functions` due to 3 previous errors; 1 warning emitted
L'istruzione let y = 6
non restituisce un valore, quindi non c'è nulla a cui x
possa legarsi. Questo è diverso da ciò che accade in altri linguaggi, come C e Ruby, dove l'assegnazione restituisce il valore dell'assegnazione. In quei linguaggi, puoi scrivere x = y = 6
e avere sia x
che y
con il valore 6
; questo non avviene in Rust.
Le espressioni valutano un valore e costituiscono la maggior parte del resto del codice che scriverai in Rust. Considera un'operazione matematica, come 5 + 6
, che è un'espressione che valuta il valore 11
. Le espressioni possono essere parte di istruzioni: nell'Elenco 3-1, il 6
nell'istruzione let y = 6;
è un'espressione che valuta il valore 6
. Chiamare una funzione è un'espressione. Chiamare una macro è un'espressione. Un nuovo blocco di scope creato con parentesi graffe è un'espressione, per esempio:
Nome del file: src/main.rs
fn main() { let y = { let x = 3; x + 1 }; println!("The value of y is: {y}"); }
Questa espressione:
{
let x = 3;
x + 1
}
è un blocco che, in questo caso, valuta il valore 4
. Tale valore viene legato a y
come parte dell'istruzione let
. Nota che la riga x + 1
non ha un punto e virgola alla fine, a differenza della maggior parte delle righe che hai visto finora. Le espressioni non includono punti e virgola alla fine. Se aggiungi un punto e virgola alla fine di un'espressione, la trasformi in un'istruzione, e quindi non restituirà un valore. Tieni presente questo mentre esplori i valori di ritorno delle funzioni e le espressioni a seguire.
Funzioni con Valori di Ritorno
Le funzioni possono restituire valori al codice che le richiama. Non diamo un nome ai valori di ritorno, ma dobbiamo dichiararne il tipo dopo una freccia (->
). In Rust, il valore di ritorno della funzione è sinonimo del valore dell'espressione finale nel blocco del corpo di una funzione. Puoi restituire prematuramente da una funzione usando la parola chiave return
e specificando un valore, ma la maggior parte delle funzioni restituisce l'ultima espressione implicitamente. Ecco un esempio di una funzione che restituisce un valore:
Nome del file: src/main.rs
fn five() -> i32 { 5 } fn main() { let x = five(); println!("The value of x is: {x}"); }
Non ci sono chiamate di funzioni, macro o addirittura istruzioni let
nella funzione five
—solo il numero 5
da solo. Questa è una funzione perfettamente valida in Rust. Nota che è specificato anche il tipo di ritorno della funzione, come -> i32
. Prova a eseguire questo codice; l'output dovrebbe essere simile al seguente:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Finished dev [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/functions`
The value of x is: 5
Il 5
in five
è il valore di ritorno della funzione, motivo per cui il tipo di ritorno è i32
. Esaminiamolo più in dettaglio. Ci sono due punti importanti: primo, la riga let x = five();
mostra che stiamo usando il valore di ritorno di una funzione per inizializzare una variabile. Poiché la funzione five
restituisce un 5
, quella riga è equivalente a quanto segue:
#![allow(unused)] fn main() { let x = 5; }
Secondo, la funzione five
non ha parametri e definisce il tipo del valore di ritorno, ma il corpo della funzione è un isolamento 5
senza punto e virgola perché è un'espressione il cui valore vogliamo restituire.
Esaminiamo un altro esempio:
Nome del file: src/main.rs
fn main() { let x = plus_one(5); println!("The value of x is: {x}"); } fn plus_one(x: i32) -> i32 { x + 1 }
Eseguire questo codice stamperà Il valore di x è: 6
. Ma se mettiamo un punto e virgola alla fine della riga che contiene x + 1
, trasformandolo da espressione in istruzione, otterremo un errore:
Nome del file: src/main.rs
fn main() {
let x = plus_one(5);
println!("The value of x is: {x}");
}
fn plus_one(x: i32) -> i32 {
x + 1;
}
Compilare questo codice produce un errore, come segue:
$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
error[E0308]: mismatched types
--> src/main.rs:7:24
|
7 | fn plus_one(x: i32) -> i32 {
| -------- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
8 | x + 1;
| - help: remove this semicolon to return this value
For more information about this error, try `rustc --explain E0308`.
error: could not compile `functions` due to previous error
Il principale messaggio di errore, mismatched types
, rivela il problema centrale di questo codice. La definizione della funzione plus_one
dice che restituirà un i32
, ma le istruzioni non valutano un valore, che è espresso da ()
, il tipo unità. Pertanto, nulla viene restituito, il che contraddice la definizione della funzione e risulta in un errore. In questo output, Rust fornisce un messaggio che potrebbe aiutare a rettificare questo problema: suggerisce di rimuovere il punto e virgola, il che risolverebbe l'errore.
Commenti
Tutti i programmatori cercano di rendere il proprio codice facile da capire, ma a volte è necessaria un'ulteriore spiegazione. In questi casi, i programmatori lasciano commenti nel loro codice sorgente che il compilatore ignorerà ma che le persone che leggono il codice sorgente possono trovare utili.
Ecco un semplice commento:
#![allow(unused)] fn main() { // hello, world }
In Rust, lo stile idiomatico dei commenti inizia con due barre oblique, e il
commento continua fino alla fine della riga. Per i commenti che si estendono oltre una
singola riga, sarà necessario includere //
su ogni riga, come questo:
#![allow(unused)] fn main() { // Quindi stiamo facendo qualcosa di complicato qui, abbastanza lungo da richiedere // più righe di commenti per spiegarlo! Uff! Speriamo che questo commento // spieghi cosa sta succedendo. }
I commenti possono anche essere posizionati alla fine delle righe contenenti codice:
Nome del file: src/main.rs
fn main() { let lucky_number = 7; // I’m feeling lucky today }
Ma li vedrai più spesso usare in questo formato, con il commento su una riga separata sopra il codice che annota:
Nome del file: src/main.rs
fn main() { // I’m feeling lucky today let lucky_number = 7; }
Rust ha anche un altro tipo di commento, commenti di documentazione, di cui parleremo nella sezione “Pubblicare un Crate su Crates.io” del Capitolo 14.
Flusso di Controllo
La capacità di eseguire un po' di codice a seconda se una condizione sia true
e di
eseguire un po' di codice ripetutamente mentre una condizione è true
sono blocchi di costruzione di base
nella maggior parte dei linguaggi di programmazione. I costrutti più comuni che ti permettono di controllare
il flusso di esecuzione del codice Rust sono le espressioni if
e i cicli.
Espressioni if
Un'espressione if
ti permette di ramificare il tuo codice a seconda delle condizioni. Tu
fornisci una condizione e poi dichiari: "Se questa condizione è soddisfatta, esegui questo blocco
di codice. Se la condizione non è soddisfatta, non eseguire questo blocco di codice."
Crea un nuovo progetto chiamato branches nella tua directory projects per esplorare
l'espressione if
. Nel file src/main.rs, inserisci il seguente codice:
Nome del file: src/main.rs
fn main() { let number = 3; if number < 5 { println!("condition was true"); } else { println!("condition was false"); } }
Tutte le espressioni if
iniziano con la parola chiave if
, seguita da una condizione. In
questo caso, la condizione verifica se la variabile number
ha un valore inferiore a 5. Poniamo
il blocco di codice da eseguire se la condizione è true
immediatamente dopo la condizione all'interno delle
parentesi graffe. I blocchi di codice associati alle condizioni nelle espressioni if
a volte sono chiamati bracci,
proprio come i bracci nelle espressioni match
di cui abbiamo parlato nella sezione “Comparare
la Predizione con il Numero Segreto” del Capitolo 2.
Facoltativamente, possiamo anche includere un'espressione else
, come abbiamo scelto di fare
qui, per dare al programma un blocco alternativo di codice da eseguire se
la condizione risulta false
. Se non si fornisce un'espressione else
e
la condizione è false
, il programma salterà semplicemente il blocco if
e passerà
alla prossima porzione di codice.
Prova a eseguire questo codice; dovresti vedere il seguente output:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was true
Proviamo a cambiare il valore di number
a un valore che rende la condizione
false
per vedere cosa succede:
fn main() {
let number = 7;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
Esegui di nuovo il programma e guarda l'output:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
condition was false
Vale anche la pena notare che la condizione in questo codice deve essere un bool
. Se
la condizione non è un bool
, otterremo un errore. Ad esempio, prova a eseguire il
seguente codice:
Nome del file: src/main.rs
fn main() {
let number = 3;
if number {
println!("number was three");
}
}
La condizione if
questa volta valuta un valore di 3
, e Rust lancia un
errore:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: mismatched types
--> src/main.rs:4:8
|
4 | if number {
| ^^^^^^ expected `bool`, found integer
For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` due to previous error
L'errore indica che Rust si aspettava un bool
ma ha ottenuto un integer. A differenza
di linguaggi come Ruby e JavaScript, Rust non tenterà automaticamente
di convertire tipi non booleani in un Booleano. Devi essere esplicito e fornire sempre
if
con un Booleano come condizione. Se vogliamo che il blocco di codice if
venga
eseguito solo quando un numero non è uguale a 0
, ad esempio, possiamo cambiare l'espressione if
nel modo seguente:
Nome del file: src/main.rs
fn main() { let number = 3; if number != 0 { println!("number was something other than zero"); } }
Eseguire questo codice stamperà number was something other than zero
.
Gestione di Più Condizioni con else if
Puoi usare più condizioni combinando if
e else
in un'espressione else if
.
Ad esempio:
Nome del file: src/main.rs
fn main() { let number = 6; if number % 4 == 0 { println!("number is divisible by 4"); } else if number % 3 == 0 { println!("number is divisible by 3"); } else if number % 2 == 0 { println!("number is divisible by 2"); } else { println!("number is not divisible by 4, 3, or 2"); } }
Questo programma ha quattro possibili percorsi che può seguire. Dopo averlo eseguito, dovresti vedere il seguente output:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/branches`
number is divisible by 3
Quando questo programma viene eseguito, verifica ogni espressione if
a turno ed esegue
il primo corpo per cui la condizione valuta true
. Nota che anche se 6 è divisibile per 2, non vediamo l'output number is divisible by 2
,
né vediamo il testo number is not divisible by 4, 3, or 2
dal blocco else
. Questo perché Rust esegue solo il blocco per la prima condizione true
,
e una volta trovata una, non verifica nemmeno le restanti.
Usare troppe espressioni else if
può rendere il tuo codice ingombrante, quindi se hai
più di una, potresti voler rifattorizzare il tuo codice. Il Capitolo 6 descrive un potente
costrutto di ramificazione di Rust chiamato match
per questi casi.
Uso di if
in una Dichiarazione let
Poiché if
è un'espressione, possiamo usarla sul lato destro di una dichiarazione let
per assegnare il risultato a una variabile, come mostrato nell'Elenco 3-2.
fn main() { let condition = true; let number = if condition { 5 } else { 6 }; println!("The value of number is: {number}"); }
La variabile number
sarà legata a un valore basato sul risultato dell'espressione if
.
Esegui questo codice per vedere cosa succede:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Finished dev [unoptimized + debuginfo] target(s) in 0.30s
Running `target/debug/branches`
The value of number is: 5
Ricorda che i blocchi di codice valutano l'ultima espressione al loro interno, e
i numeri da soli sono anche espressioni. In questo caso, il valore dell'intera espressione if
dipende da quale blocco di codice viene eseguito. Questo significa che i valori che hanno il potenziale di essere risultati di ogni braccio dell'espressione if
devono essere
dello stesso tipo; nell'Elenco 3-2, i risultati di entrambi i bracci if
e else
erano numeri interi i32
. Se i tipi non corrispondono, come nel seguente
esempio, otterremo un errore:
Nome del file: src/main.rs
fn main() {
let condition = true;
let number = if condition { 5 } else { "six" };
println!("The value of number is: {number}");
}
Quando proveremo a compilare questo codice, otterremo un errore. I bracci if
e else
hanno tipi di valore incompatibili, e Rust indica esattamente dove trovare il problema all'interno del programma:
$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
error[E0308]: `if` and `else` have incompatible types
--> src/main.rs:4:44
|
4 | let number = if condition { 5 } else { "six" };
| - ^^^^^ expected integer, found `&str`
| |
| expected because of this
For more information about this error, try `rustc --explain E0308`.
error: could not compile `branches` due to previous error
L'espressione nel blocco if
valuta a un numero intero, e l'espressione nel
blocco else
valuta a una stringa. Questo non funzionerà perché le variabili devono
avere un singolo tipo, e Rust ha bisogno di sapere al momento della compilazione di quale tipo
è la variabile number
, in modo definitivo. Conoscere il tipo di number
permette al
compilatore di verificare che il tipo sia valido ovunque utilizziamo number
. Rust non sarebbe
in grado di farlo se il tipo di number
fosse determinato solo a runtime; il
compilatore sarebbe più complesso e farebbe meno garanzie sul codice se
dovesse tenere traccia di più tipi ipotetici per qualsiasi variabile.
Ripetizione con i Cicli
Spesso è utile eseguire un blocco di codice più di una volta. Per questo compito, Rust fornisce diversi cicli, che eseguiranno il codice all'interno del corpo del ciclo fino alla fine e poi ripartiranno immediatamente dall'inizio. Per sperimentare con i cicli, creiamo un nuovo progetto chiamato loops.
Rust ha tre tipi di cicli: loop
, while
, e for
. Proviamoli tutti.
Ripetere Codice con loop
La parola chiave loop
dice a Rust di eseguire un blocco di codice più e più volte
per sempre o finché non gli dici esplicitamente di fermarsi.
Come esempio, cambia il file src/main.rs nella tua directory loops per assomigliare a questo:
Nome del file: src/main.rs
fn main() {
loop {
println!("again!");
}
}
Quando eseguiamo questo programma, vedremo again!
stampato più e più volte continuamente
finché non interrompiamo manualmente il programma. La maggior parte dei terminali supporta la scorciatoia da tastiera
ctrl-c per interrompere un programma che è bloccato in un ciclo continuo. Prova:
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!
Il simbolo ^C
rappresenta dove hai premuto ctrl-c. Potresti
vedere o meno la parola again!
stampata dopo il ^C
, a seconda di dove
il codice si trovava nel ciclo quando ha ricevuto il segnale di interruzione.
Fortunatamente, Rust fornisce anche un modo per uscire da un ciclo utilizzando il codice. Puoi
posizionare la parola chiave break
all'interno del ciclo per dire al programma quando smettere
di eseguire il ciclo. Ricorda che abbiamo fatto questo nel gioco delle ipotesi nella
sezione “Uscire Dopo un'Ipotesi Corretta” del Capitolo 2 per uscire dal programma quando l'utente ha vinto il gioco indovinando
il numero corretto.
Abbiamo anche usato continue
nel gioco delle ipotesi, che in un ciclo dice al programma
di saltare qualsiasi codice rimanente in questa iterazione del ciclo e andare alla
successiva iterazione.
Ritornare Valori dai Cicli
Uno degli usi di un loop
è riprovare un'operazione che sai potrebbe fallire, come
verificare se un thread ha completato il suo lavoro. Potresti anche aver bisogno di passare
il risultato di quell'operazione fuori dal ciclo al resto del tuo codice. Per
fare ciò, puoi aggiungere il valore che vuoi ritornato dopo l'espressione break
che usi
per fermare il ciclo; quel valore verrà restituito fuori dal ciclo in modo che tu possa
usarlo, come mostrato qui:
fn main() { let mut counter = 0; let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; println!("The result is {result}"); }
Prima del ciclo, dichiariamo una variabile chiamata counter
e la inizializziamo a
0
. Poi dichiariamo una variabile chiamata result
per contenere il valore restituito
dal ciclo. Ad ogni iterazione del ciclo, aggiungiamo 1
alla variabile counter
,
e poi verifichiamo se il counter
è uguale a 10
. Quando lo è, usiamo la
parola chiave break
con il valore counter * 2
. Dopo il ciclo, utilizziamo un
punto e virgola per terminare l'istruzione che assegna il valore a result
. Infine, stampiamo
il valore in result
, che in questo caso è 20
.
Puoi anche utilizzare return
all'interno di un ciclo. Mentre break
esce solo dal ciclo corrente, return
esce sempre dalla funzione corrente.
Etichette di Ciclo per Disambiguare tra Più Cicli
Se hai cicli all'interno di cicli, break
e continue
si applicano al ciclo più interno
in quel punto. Puoi facoltativamente specificare un'etichetta di ciclo su un ciclo che puoi
usare poi con break
o continue
per specificare che quelle parole chiave
si applicano al ciclo etichettato anziché al ciclo più interno. Le etichette di ciclo devono iniziare
con un singolo apostrofo. Ecco un esempio con due cicli innestati:
fn main() { let mut count = 0; 'counting_up: loop { println!("count = {count}"); let mut remaining = 10; loop { println!("remaining = {remaining}"); if remaining == 9 { break; } if count == 2 { break 'counting_up; } remaining -= 1; } count += 1; } println!("End count = {count}"); }
Il ciclo esterno ha l'etichetta 'counting_up
, e conterà da 0 a 2.
Il ciclo interno senza etichetta conta a ritroso da 10 a 9. Il primo break
che
non specifica un'etichetta uscirà solo dal ciclo interno. L'istruzione break 'counting_up;
uscirà dal ciclo esterno. Questo codice stampa:
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished dev [unoptimized + debuginfo] target(s) in 0.58s
Running `target/debug/loops`
count = 0
remaining = 10
remaining = 9
count = 1
remaining = 10
remaining = 9
count = 2
remaining = 10
End count = 2
Cicli Condizionali con while
Un programma avrà spesso bisogno di valutare una condizione all'interno di un ciclo. Mentre
la condizione è true
, il ciclo si esegue. Quando la condizione cessa di essere true
, il
programma chiama break
, interrompendo il ciclo. È possibile implementare un
comportamento come questo utilizzando una combinazione di loop
, if
, else
, e break
; puoi
provare a farlo ora in un programma, se vuoi. Tuttavia, questo pattern è così comune
che Rust ha un costrutto integrato per esso, chiamato ciclo while
. Nell'Elenco 3-3,
usiamo while
per eseguire il programma tre volte, contando ogni volta, e poi, dopo il ciclo, stampare un messaggio ed uscire.
fn main() { let mut number = 3; while number != 0 { println!("{number}!"); number -= 1; } println!("LIFTOFF!!!"); }
Questo costrutto elimina molta nidificazione che sarebbe necessaria se avessi usato
loop
, if
, else
, e break
, ed è più chiaro. Mentre una condizione
valuta come true
, il codice viene eseguito; altrimenti, esce dal ciclo.
Ciclare Attraverso una Collezione con for
Puoi anche usare il costrutto while
per cicli sugli elementi di una
collezione, come un array. Ad esempio, il ciclo nell'Elenco 3-4 stampa ciascun
elemento nell'array a
.
fn main() { let a = [10, 20, 30, 40, 50]; let mut index = 0; while index < 5 { println!("the value is: {}", a[index]); index += 1; } }
Qui, il codice conta attraverso gli elementi nell'array. Inizia dall'indice
0
, e quindi cicla finché non raggiunge l'indice finale nell'array (cioè,
quando index < 5
non è più true
). Eseguendo questo codice, stamperà ogni
elemento nell'array:
$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Finished dev [unoptimized + debuginfo] target(s) in 0.32s
Running `target/debug/loops`
the value is: 10
the value is: 20
the value is: 30
the value is: 40
the value is: 50
Tutti e cinque i valori dell'array compaiono nel terminale, come previsto. Anche se index
raggiungerà un valore di 5
ad un certo punto, il ciclo smette di eseguire prima di tentare
di recuperare un sesto valore dall'array.
Tuttavia, questo approccio è incline a errori; potremmo far sì che il programma vada in panic se
il valore dell'indice o la condizione di verifica è errata. Ad esempio, se cambi il
radicamento dell'array a
per avere quattro elementi ma ti dimentichi di aggiornare la
condizione a while index < 4
, il codice andrebbe in panic. È anche lento, perché
il compilatore aggiunge runtime di codice per eseguire il controllo condizionale sel'indice è all'interno dei limiti dell'array ad ogni iterazione attraverso il ciclo.
Come alternativa più concisa, puoi utilizzare un ciclo for
ed eseguire del codice
per ciascun elemento in una collezione. Un ciclo for
sembra il codice nell'Elenco 3-5.
fn main() { let a = [10, 20, 30, 40, 50]; for element in a { println!("the value is: {element}"); } }
Quando eseguiamo questo codice, vedremo lo stesso output dell'Elenco 3-4. Più importante, abbiamo ora aumentato la sicurezza del codice ed eliminato la possibilità di bug che potrebbero derivare dall'andare oltre la fine dell'array o dal non andare abbastanza lontano e perdere alcuni elementi.
Utilizzando il ciclo for
, non devi ricordarti di cambiare alcun altro codice se
cambi il numero di valori nell'array, come faresti con il metodo
usato nell'Elenco 3-4.
La sicurezza e la concisione dei cicli for
li rendono la struttura di ciclo più comunemente usata in Rust. Anche in situazioni in cui si desidera eseguire un certo numero di volte un certo codice, come nell'esempio del conto alla rovescia che utilizzava un ciclo while
nel Listing 3-3, la maggior parte dei Rustaceans userebbero un ciclo for
. Il modo per farlo è utilizzare un Range
, fornito dalla libreria standard, che genera tutti i numeri in sequenza a partire da un numero e terminando prima di un altro numero.
Ecco come apparirebbe il conto alla rovescia usando un ciclo for
e un altro metodo di cui non abbiamo ancora parlato, rev
, per invertire l'intervallo:
Nome del file: src/main.rs
fn main() { for number in (1..4).rev() { println!("{number}!"); } println!("LIFTOFF!!!"); }
Questo codice è un po' più bello, vero?
Riepilogo
Ce l'hai fatta! Questo è stato un capitolo considerevole: hai imparato variabili, tipi di dati scalari e composti, funzioni, commenti, espressioni if
e cicli! Per esercitarti con i concetti discussi in questo capitolo, prova a costruire dei programmi per fare quanto segue:
- Convertire le temperature tra Fahrenheit e Celsius.
- Generare il numero Fibonacci n-esimo.
- Stampare il testo della canzone natalizia “The Twelve Days of Christmas”, sfruttando la ripetizione nella canzone.
Quando sei pronto per andare avanti, parleremo di un concetto in Rust che non esiste comunemente in altri linguaggi di programmazione: ownership.
Comprendere Ownership
Ownership è la caratteristica più unica di Rust e ha profonde implicazioni per il resto del linguaggio. Permette a Rust di fare garanzie di sicurezza della memoria senza aver bisogno di un garbage collector, quindi è importante capire come funziona ownership. In questo capitolo, parleremo di ownership così come di molte caratteristiche correlate: borrowing, slices, e come Rust dispone i dati in memoria.
Cos'è la Ownership?
Ownership è un insieme di regole che governano come un programma Rust gestisce la memoria. Tutti i programmi devono gestire il modo in cui utilizzano la memoria di un computer mentre sono in esecuzione. Alcuni linguaggi hanno la raccolta automatica della memoria (garbage collection) che regolarmente cerca la memoria non più utilizzata mentre il programma è in esecuzione; in altri linguaggi, il programmatore deve allocare e liberare esplicitamente la memoria. Rust usa un terzo approccio: la memoria viene gestita attraverso un sistema di ownership con un insieme di regole che il compilatore verifica. Se una qualsiasi delle regole viene violata, il programma non verrà compilato. Nessuna delle caratteristiche dell'ownership rallenterà il tuo programma mentre è in esecuzione.
Poiché l'ownership è un concetto nuovo per molti programmatori, richiede un po' di tempo per abituarsi. La buona notizia è che più acquisisci esperienza con Rust e le regole del sistema di ownership, più facilmente svilupperai naturalmente del codice sicuro ed efficiente. Continua a provarci!
Quando capirai l'ownership, avrai una solida base per comprendere le caratteristiche che rendono Rust unico. In questo capitolo, imparerai l'ownership attraverso alcuni esempi che si concentrano su una struttura dati molto comune: le stringhe.
Lo Stack e l'Heap
Molti linguaggi di programmazione non richiedono di pensare spesso allo stack e all'heap. Ma in un linguaggio di programmazione di sistema come Rust, se un valore è nello stack o nell'heap influisce su come si comporta il linguaggio e perché devi prendere determinate decisioni. Parti dell'ownership verranno descritte in relazione allo stack e all'heap più avanti in questo capitolo, quindi ecco una breve spiegazione per prepararti.
Sia lo stack che l'heap sono parti della memoria disponibili per il tuo codice da usare durante l'esecuzione, ma sono strutturati in modi diversi. Lo stack memorizza valori nell'ordine in cui li riceve e rimuove i valori nell'ordine opposto. Questo è chiamato last in, first out. Pensa a una pila di piatti: quando aggiungi più piatti, li metti in cima alla pila, e quando hai bisogno di un piatto, ne prendi uno dalla cima. Aggiungere o rimuovere piatti dal centro o dal fondo non funzionerebbe altrettanto bene! Aggiungere dati è chiamato pushing onto the stack, e rimuovere dati è chiamato popping off the stack. Tutti i dati memorizzati nello stack devono avere una dimensione nota e fissa. I dati con una dimensione sconosciuta durante la compilazione o con una dimensione che potrebbe cambiare devono essere memorizzati nell'heap.
L'heap è meno organizzato: quando metti dati nell'heap, richiedi una certa quantità di spazio. Il memory allocator trova uno spazio vuoto nell'heap abbastanza grande, lo segna come in uso e restituisce un puntatore, che è l'indirizzo di quella posizione. Questo processo è chiamato allocating on the heap ed è talvolta abbreviato in allocating (pushare i valori nello stack non è considerato allocare). Poiché il puntatore all'heap è di una dimensione nota e fissa, puoi memorizzare il puntatore nello stack, ma quando vuoi i dati effettivi, devi seguire il puntatore. Pensa a essere seduto in un ristorante. Quando entri, dichiarala il numero di persone nel tuo gruppo, e l'host trova un tavolo vuoto che si adatti a tutti e ti ci accompagna. Se qualcuno del tuo gruppo arriva in ritardo, può chiedere dove siete stati seduti per trovarvi.
Pushare nello stack è più veloce rispetto ad allocare nell'heap perché il allocatore non deve mai cercare un posto dove memorizzare i nuovi dati; quella posizione è sempre in cima allo stack. Comparativamente, allocare spazio nell'heap richiede più lavoro perché l'allocatore deve prima trovare uno spazio abbastanza grande da contenere i dati e poi eseguire operazioni di bookkeeping per prepararsi alla prossima allocazione.
Accedere ai dati nell'heap è più lento rispetto ad accedere ai dati nello stack perché devi seguire un puntatore per arrivarci. I processori contemporanei sono più veloci se saltano meno in memoria. Continuando l'analogia, considera un cameriere in un ristorante che prende ordini da molti tavoli. È più efficiente raccogliere tutti gli ordini a un tavolo prima di passare al prossimo. Prendere un ordine dal tavolo A, quindi un ordine dal tavolo B, quindi un altro ordine da A e poi un altro da B sarebbe un processo molto più lento. Allo stesso modo, un processore può fare meglio il suo lavoro se lavora su dati che sono vicini ad altri dati (come nello stack) piuttosto che più lontani (come può essere nell'heap).
Quando il tuo codice chiama una funzione, i valori passati nella funzione (compresi, potenzialmente, i puntatori ai dati nell'heap) e le variabili locali della funzione vengono pushate nello stack. Quando la funzione termina, quei valori vengono poppati dallo stack.
Tenere traccia di quali parti del codice stanno utilizzando quali dati nell'heap, minimizzare la quantità di dati duplicati nell'heap, e pulire i dati non utilizzati nell'heap in modo da non esaurire lo spazio sono tutti problemi che l'ownership affronta. Una volta che capirai l'ownership, non dovrai pensare spesso allo stack e all'heap, ma sapere che l'obiettivo principale dell'ownership è gestire i dati nell'heap può aiutare a spiegare perché funziona in questo modo.
Regole dell'Ownership
Per prima cosa, diamo un'occhiata alle regole dell'ownership. Tieni a mente queste regole mentre procediamo attraverso gli esempi che le illustrano:
- Ogni valore in Rust ha un owner.
- Può esserci solo un owner alla volta.
- Quando l'owner esce dallo scope, il valore verrà rilasciato.
Scope delle Variabili
Ora che abbiamo superato la sintassi base di Rust, non includeremo tutto il codice fn main() {
negli esempi, quindi se stai seguendo, assicurati di inserire i seguenti
esempi manualmente all'interno di una funzione main
. Di conseguenza, i nostri esempi saranno
un po' più concisi, permettendoci di concentrarci sui dettagli effettivi piuttosto che
sul codice boilerplate.
Come primo esempio di ownership, daremo un'occhiata allo scope di alcune variabili. Uno scope è l'intervallo all'interno di un programma per il quale un elemento è valido. Prendi la seguente variabile:
#![allow(unused)] fn main() { let s = "hello"; }
La variabile s
si riferisce a un literal di stringa, dove il valore della stringa è
codificato nel testo del nostro programma. La variabile è valida dal momento in cui
viene dichiarata fino alla fine dell'attuale scope. Listing 4-1 mostra un programma con commenti che annotano dove la variabile s
sarebbe valida.
fn main() { { // s is not valid here, it’s not yet declared let s = "hello"; // s is valid from this point forward // do stuff with s } // this scope is now over, and s is no longer valid }
In altre parole, ci sono due importanti punti nel tempo qui:
- Quando
s
entra nello scope, è valida. - Rimane valida fino a quando esce dallo scope.
A questo punto, la relazione tra gli scope e quando le variabili sono valide è
simile a quella di altri linguaggi di programmazione. Ora costruiremo su questa
comprensione introducendo il tipo String
.
Il Tipo String
Per illustrare le regole dell'ownership, abbiamo bisogno di un tipo di dato più complesso
di quelli trattati nella sezione “Tipi di Dato” del Capitolo 3. I tipi trattati in precedenza sono di dimensioni conosciute, possono essere memorizzati
sullo stack e poppati dallo stack quando il loro scope è finito, e possono essere
rapidamente e facilmente copiati per creare una nuova istanza indipendente se un'altra
parte del codice ha bisogno di utilizzare lo stesso valore in un diverso scope. Ma vogliamo
esaminare i dati che sono memorizzati nell'heap ed esplorare come Rust sa quando
pulire quei dati, e il tipo String
è un ottimo esempio.
Ci concentreremo sulle parti di String
che riguardano l'ownership. Questi
aspetti si applicano anche ad altri tipi di dati complessi, siano essi forniti dalla
libreria standard o creati da te. Discuteremo String
più in dettaglio nel
Capitolo 8.
Abbiamo già visto i literal di stringa, dove un valore di stringa è codificato nel nostro
programma. I literal di stringa sono convenienti, ma non sono adatti a ogni
situazione in cui potremmo voler usare il testo. Un motivo è che sono
immutabili. Un altro è che non tutti i valori delle stringhe possono essere conosciuti quando scriviamo il nostro
codice: per esempio, cosa succede se vogliamo prendere l'input dell'utente e memorizzarlo? Per
queste situazioni, Rust ha un secondo tipo di stringa, String
. Questo tipo gestisce
dati allocati nell'heap e come tale è in grado di memorizzare una quantità di testo che
non conosciamo in fase di compilazione. Puoi creare un String
da un literal di stringa
usando la funzione from
, in questo modo:
#![allow(unused)] fn main() { let s = String::from("hello"); }
Il doppio due punti ::
dell'operatore ci consente di usare questo particolare from
all'interno del tipo String
anziché utilizzare un qualche tipo di nome come
string_from
. Discuteremo questa sintassi più nella sezione “Metodo
Sintassi” del Capitolo 5 e quando parleremo della creazione di namespace con i moduli in “Percorsi per riferirsi a un elemento nell'albero dei moduli” nel Capitolo 7.
Questo tipo di stringa può essere mutato:
fn main() { let mut s = String::from("hello"); s.push_str(", world!"); // push_str() appends a literal to a String println!("{}", s); // This will print `hello, world!` }
Quindi, qual è la differenza qui? Perché String
può essere mutata ma i literal
no? La differenza sta in come questi due tipi gestiscono la memoria.
Memoria e Allocazione
Nel caso di un literal di stringa, conosciamo il contenuto in fase di compilazione, quindi il testo è codificato direttamente nel file eseguibile finale. Questo è il motivo per cui i literal di stringa sono rapidi ed efficienti. Ma queste proprietà derivano solo dall'immutabilità del literal di stringa. Sfortunatamente, non possiamo mettere una quantità indefinita di memoria nel binario per ogni pezzo di testo la cui dimensione è sconosciuta in fase di compilazione e la cui dimensione potrebbe cambiare durante l'esecuzione del programma.
Con il tipo String
, al fine di supportare un pezzo di testo mutabile e che
può crescere, dobbiamo allocare una quantità di memoria nell'heap, sconosciuta in fase di compilazione, per
contenere il contenuto. Questo significa:
- La memoria deve essere richiesta dal memory allocator a runtime.
- Abbiamo bisogno di un modo per restituire questa memoria all'allocator quando abbiamo finito con
il nostro
String
.
Quella prima parte è fatta da noi: quando chiamiamo String::from
, la sua implementazione richiede
la memoria di cui ha bisogno. Questo è abbastanza universale nei linguaggi di
programmazione.
Tuttavia, la seconda parte è diversa. Nei linguaggi con un garbage collector
(GC), il GC tiene traccia e pulisce la memoria che non viene più utilizzata,
e noi non dobbiamo pensarci. Nella maggior parte dei linguaggi senza un GC,
è nostra responsabilità identificare quando la memoria non viene più utilizzata e
chiamare del codice per liberarla esplicitamente, proprio come abbiamo fatto per richiederla. Fare questo in modo corretto è storicamente stato un problema di programmazione difficile.
Se ce ne dimentichiamo, sprecheremo memoria. Se lo facciamo troppo presto, avremo una variabile non valida. Se lo facciamo due volte, è anche un bug. Abbiamo bisogno di abbinare esattamente un allocate
con
esattamente un free
.
Rust prende un percorso diverso: la memoria viene automaticamente restituita una volta che la
variabile che la possiede esce dallo scope. Ecco una versione del nostro esempio di scope
dal Listing 4-1 usando una String
anziché un literal di stringa:
fn main() { { let s = String::from("hello"); // s is valid from this point forward // do stuff with s } // this scope is now over, and s is no // longer valid }
C'è un punto naturale in cui possiamo restituire la memoria di cui il nostro String
ha bisogno
all'allocator: quando s
esce dallo scope. Quando una variabile esce dallo scope,
Rust chiama una funzione speciale per noi. Questa funzione si chiama
drop
, ed è dove l'autore di String
può mettere
il codice per restituire la memoria. Rust chiama drop
automaticamente alla chiusura
della parentesi graffa.
Nota: In C++, questo pattern di deallocare risorse alla fine del ciclo di vita di un elemento è talvolta chiamato Resource Acquisition Is Initialization (RAII). La funzione
drop
in Rust sarà familiare se hai usato pattern RAII.
Questo pattern ha un impatto profondo sul modo in cui viene scritto il codice Rust. Potrebbe sembrare semplice ora, ma il comportamento del codice può essere inaspettato in situazioni più complicate quando vogliamo che più variabili utilizzino i dati che abbiamo allocato nell'heap. Esploriamo alcune di queste situazioni ora.
Variabili e Dati che Interagiscono con il Move
Più variabili possono interagire con gli stessi dati in modi diversi in Rust. Diamo un'occhiata a un esempio usando un intero nel Listing 4-2.
fn main() { let x = 5; let y = x; }
Probabilmente possiamo immaginare cosa sta facendo: “associa il valore 5
a x
; quindi fai
una copia del valore in x
e associala a y
.” Ora abbiamo due variabili, x
e y
, e entrambi valgono 5
. Questo è effettivamente ciò che sta accadendo, perché gli interi
sono valori semplici di dimensioni conosciute e fisse, e questi due valori 5
vengono pushati
nello stack.
Ora vediamo la versione con String
:
fn main() { let s1 = String::from("hello"); let s2 = s1; }
Questo sembra molto simile, quindi potremmo supporre che funzioni allo stesso modo: vale a dire, la seconda riga farebbe una copia del valore in s1
e lo assocerebbe a s2
. Ma non è proprio quello che succede.
Dai un'occhiata alla Figura 4-1 per vedere cosa sta succedendo a String
sotto il cofano. Una String
è composta da tre parti, mostrate a sinistra: un puntatore alla memoria che contiene il contenuto della stringa, una lunghezza e una capacità. Questo gruppo di dati viene memorizzato nello stack. A destra c'è la memoria sull'heap che contiene i contenuti.
La lunghezza è la quantità di memoria, in byte, che il contenuto della String
sta
attualmente utilizzando. La capacità è la quantità totale di memoria, in byte, che la
String
ha ricevuto dall'allocator. La differenza tra lunghezza e
capacità è importante, ma non in questo contesto, quindi per ora, va bene ignorare la
capacità.
Quando assegnamo s1
a s2
, i dati della String
vengono copiati, il che significa che
copia il puntatore, la lunghezza e la capacità che sono nello stack. Non copiamo i
dati nell'heap a cui il puntatore si riferisce. In altre parole, la rappresentazione in memoria sembra simile a quella della Figura 4-2.
La rappresentazione non sembra come nella Figura 4-3, che è ciò che la memoria mostrerebbe se Rust copiasse anche i dati nell'heap. Se Rust facesse questo, l'operazione s2 = s1
potrebbe essere molto costosa in termini di prestazioni runtime se i dati nell'heap fossero grandi.
In precedenza, abbiamo detto che quando una variabile esce dallo scope, Rust chiama automaticamente la funzione drop
e pulisce la memoria heap per quella variabile. Ma la Figura 4-2 mostra che entrambi i puntatori dati puntano alla stessa posizione. Questo è un problema: quando s2
e s1
escono dallo scope, entrambi tenteranno di liberare la stessa memoria. Questo è noto come un errore di doppia liberazione ed è uno dei bug di sicurezza della memoria che abbiamo menzionato in precedenza. La liberazione della memoria due volte può portare alla corruzione della memoria, il che può potenzialmente portare a vulnerabilità di sicurezza.
Per garantire la sicurezza della memoria, dopo la linea let s2 = s1;
, Rust considera s1
non più valido. Pertanto, Rust non ha bisogno di liberare nulla quando s1
esce dallo scope. Guarda cosa succede quando provi a usare s1
dopo che s2
è stato creato; non funzionerà:
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}, world!", s1);
}
Riceverai un errore simile a questo perché Rust ti impedisce di usare il riferimento invalidato:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
--> src/main.rs:5:28
|
2 | let s1 = String::from("hello");
| -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{}, world!", s1);
| ^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
3 | let s2 = s1.clone();
| ++++++++
For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership` due to previous error
Se hai sentito i termini shallow copy e deep copy mentre lavori con altri linguaggi, il concetto di copiare il puntatore, la lunghezza e la capacità senza copiare i dati probabilmente ti sembra quello di fare una shallow copy. Ma poiché Rust invalida anche la prima variabile, anziché essere chiamata una shallow copy, è conosciuta come una move. In questo esempio, diremmo che s1
è stato spostato in s2
. Quindi, ciò che accade effettivamente è mostrato nella Figura 4-4.
Questo risolve il nostro problema! Con solo s2
valido, quando esce dallo scope libererà da solo la memoria, e avremo finito.
Inoltre, c'è una scelta di progettazione implicita in questo: Rust non creerà mai automaticamente copie "profonde" dei tuoi dati. Pertanto, qualsiasi copia automatica può essere considerata poco costosa in termini di prestazioni di runtime.
Variabili e dati che interagiscono con Clone
Se vogliamo eseguire una copia profonda dei dati heap del String
, non solo dei dati dello stack, possiamo utilizzare un metodo comune chiamato clone
. Discuteremo la sintassi dei metodi nel Capitolo 5, ma poiché i metodi sono una caratteristica comune in molti linguaggi di programmazione, probabilmente li hai già visti.
Ecco un esempio del metodo clone
in azione:
fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); println!("s1 = {}, s2 = {}", s1, s2); }
Questo funziona perfettamente e produce esplicitamente il comportamento mostrato nella Figura 4-3, dove i dati dell'heap vengono copiati.
Quando vedi una chiamata a clone
, saprai che è in esecuzione qualche codice arbitrario e che quel codice potrebbe essere costoso. È un indicatore visivo che qualcosa di diverso sta accadendo.
Dati solo dello stack: Copy
C'è un'altra piega di cui non abbiamo ancora parlato. Questo codice che utilizza numeri interi—parte del quale è mostrata nel Listing 4-2—funziona ed è valido:
fn main() { let x = 5; let y = x; println!("x = {}, y = {}", x, y); }
Ma questo codice sembra contraddire ciò che abbiamo appena imparato: non abbiamo una chiamata a clone
, ma x
è ancora valido e non è stato spostato in y
.
La ragione è che tipi come gli interi che hanno una dimensione nota a tempo di compilazione sono conservati interamente nello stack, quindi le copie dei valori effettivi sono rapide da fare. Ciò significa che non c'è motivo per cui vorremmo impedire che x
sia valido dopo aver creato la variabile y
. In altre parole, non c'è differenza tra copia profonda e superficiale qui, quindi chiamare clone
non farebbe nulla di diverso dalla copia superficiale abituale, e possiamo lasciarlo fuori.
Rust ha un'annotazione speciale chiamata il trait Copy
che possiamo applicare ai tipi che sono conservati nello stack, come gli interi (parleremo più dei traits nel Capitolo 10). Se un tipo implementa il trait Copy
, le variabili che lo utilizzano non si spostano, ma vengono copiate in modo banale, rendendole ancora valide dopo l'assegnazione ad un'altra variabile.
Rust non ci permetterà di annotare un tipo con Copy
se il tipo, o una qualsiasi delle sue parti, ha implementato il trait Drop
. Se il tipo necessita di qualcosa di speciale quando il valore esce dallo scope e aggiungiamo l'annotazione Copy
a quel tipo, otterremo un errore a tempo di compilazione. Per imparare come aggiungere l'annotazione Copy
al tuo tipo per implementare il trait, vedi “Derivable Traits” nell'Appendice C.
Quindi, quali tipi implementano il trait Copy
? Puoi controllare la documentazione per il tipo dato per esserne sicuro, ma come regola generale, qualsiasi gruppo di valori scalari semplici può implementare Copy
, e nulla che richiede allocazione o è una qualche forma di risorsa può implementare Copy
. Ecco alcuni dei tipi che implementano Copy
:
- Tutti i tipi interi, come
u32
. - Il tipo booleano,
bool
, con valoritrue
efalse
. - Tutti i tipi a virgola mobile, come
f64
. - Il tipo carattere,
char
. - Tuple, se contengono solo tipi che implementano anche
Copy
. Ad esempio,(i32, i32)
implementaCopy
, ma(i32, String)
no.
Ownership e funzioni
La meccanica del passare un valore a una funzione è simile a quella dell'assegnare un valore a una variabile. Passare una variabile a una funzione la sposterà o copierà, proprio come fa l'assegnazione. Il Listing 4-3 contiene un esempio con alcune annotazioni che mostrano dove le variabili entrano ed escono dallo scope.
Nome del file: src/main.rs
fn main() { let s = String::from("hello"); // s comes into scope takes_ownership(s); // s's value moves into the function... // ... and so is no longer valid here let x = 5; // x comes into scope makes_copy(x); // x would move into the function, // but i32 is Copy, so it's okay to still // use x afterward } // Here, x goes out of scope, then s. But because s's value was moved, nothing // special happens. fn takes_ownership(some_string: String) { // some_string comes into scope println!("{}", some_string); } // Here, some_string goes out of scope and `drop` is called. The backing // memory is freed. fn makes_copy(some_integer: i32) { // some_integer comes into scope println!("{}", some_integer); } // Here, some_integer goes out of scope. Nothing special happens.
Se proviamo a usare s
dopo la chiamata a takes_ownership
, Rust restituirà un errore a tempo di compilazione. Questi controlli statici ci proteggono dagli errori. Prova ad aggiungere codice a main
che utilizza s
e x
per vedere dove puoi usarli e dove le regole di ownership ti impediscono di farlo.
Valori di ritorno e scope
Restituire valori può anche trasferire l'ownership. Il Listing 4-4 mostra un esempio di una funzione che restituisce un valore, con annotazioni simili a quelle del Listing 4-3.
Nome del file: src/main.rs
fn main() { let s1 = gives_ownership(); // gives_ownership moves its return // value into s1 let s2 = String::from("hello"); // s2 comes into scope let s3 = takes_and_gives_back(s2); // s2 is moved into // takes_and_gives_back, which also // moves its return value into s3 } // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing // happens. s1 goes out of scope and is dropped. fn gives_ownership() -> String { // gives_ownership will move its // return value into the function // that calls it let some_string = String::from("yours"); // some_string comes into scope some_string // some_string is returned and // moves out to the calling // function } // This function takes a String and returns one fn takes_and_gives_back(a_string: String) -> String { // a_string comes into // scope a_string // a_string is returned and moves out to the calling function }
L'ownership di una variabile segue lo stesso schema ogni volta: assegnare un valore a un'altra variabile lo sposta. Quando una variabile che include dati nell'heap esce dallo scope, il valore verrà pulito da drop
a meno che l'ownership dei dati non sia stata trasferita a un'altra variabile.
Anche se questo funziona, prendere l'ownership e poi restituire l'ownership con ogni funzione è un po' tedioso. Cosa succederebbe se volessimo permettere a una funzione di usare un valore ma non prenderne l'ownership? È piuttosto fastidioso che qualsiasi cosa passiamo debba anche essere restituita se vogliamo usarla di nuovo, oltre a qualsiasi dato risultante dal corpo della funzione che potremmo voler restituire.
Rust ci permette di restituire valori multipli usando una tupla, come mostrato nel Listing 4-5.
Nome del file: src/main.rs
fn main() { let s1 = String::from("hello"); let (s2, len) = calculate_length(s1); println!("The length of '{}' is {}.", s2, len); } fn calculate_length(s: String) -> (String, usize) { let length = s.len(); // len() returns the length of a String (s, length) }
Ma questo è troppo cerimoniale e molto lavoro per un concetto che dovrebbe essere comune. Fortunatamente per noi, Rust ha una caratteristica per utilizzare un valore senza trasferire l'ownership, chiamata references.
Riferimenti e Borrowing
Il problema con il codice della tupla in Listing 4-5 è che dobbiamo restituire lo String
alla funzione chiamante affinché possiamo ancora usare lo String
dopo la chiamata a calculate_length
, poiché lo String
è stato spostato in calculate_length
. Invece, possiamo fornire un riferimento al valore dello String
. Un riferimento è come un puntatore in quanto è un indirizzo che possiamo seguire per accedere ai dati memorizzati in quell'indirizzo; quei dati sono di proprietà di qualche altra variabile. A differenza di un puntatore, un riferimento è garantito per puntare a un valore valido di un particolare tipo per la durata di quel riferimento.
Ecco come definiremo e utilizzeremo una funzione calculate_length
che ha un riferimento a un oggetto come parametro anziché prendere possesso del valore:
Nome del file: src/main.rs
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); } fn calculate_length(s: &String) -> usize { s.len() }
Innanzitutto, nota che tutto il codice della tupla nella dichiarazione della variabile e il valore di ritorno della funzione è sparito. In secondo luogo, nota che passiamo &s1
in calculate_length
e, nella sua definizione, prendiamo &String
anziché String
. Questi simboli di e commerciale rappresentano i riferimenti e permettono di riferirsi a un valore senza prenderne possesso. La Figura 4-5 illustra questo concetto.
Nota: L'opposto di riferirsi usando
&
è dereferenziare, che si ottiene con l'operatore di dereferenziazione,*
. Vedremo alcuni usi dell'operatore di dereferenziazione nel Capitolo 8 e discuteremo i dettagli della dereferenziazione nel Capitolo 15.
Osserviamo più da vicino la chiamata della funzione qui:
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); } fn calculate_length(s: &String) -> usize { s.len() }
La sintassi &s1
ci consente di creare un riferimento che si riferisce al valore di s1
ma non ne ha il possesso. Poiché non ne ha il possesso, il valore a cui punta non verrà eliminato quando il riferimento smette di essere utilizzato.
Allo stesso modo, la firma della funzione usa &
per indicare che il tipo del parametro s
è un riferimento. Aggiungiamo alcune annotazioni esplicative:
fn main() { let s1 = String::from("hello"); let len = calculate_length(&s1); println!("The length of '{}' is {}.", s1, len); } fn calculate_length(s: &String) -> usize { // s is a reference to a String s.len() } // Here, s goes out of scope. But because it does not have ownership of what // it refers to, it is not dropped.
Lo scope in cui la variabile s
è valida è lo stesso come per qualsiasi parametro di funzione, ma il valore puntato dal riferimento non viene eliminato quando s
smette di essere utilizzato, perché s
non ne ha il possesso. Quando le funzioni hanno riferimenti come parametri anziché i valori effettivi, non avremo bisogno di restituire i valori per restituire il possesso, perché non ne avevamo mai il possesso.
Chiamiamo l'azione di creare un riferimento borrowing. Come nella vita reale, se una persona possiede qualcosa, puoi prenderlo in prestito da loro. Quando hai finito, devi restituirlo. Non lo possiedi.
Quindi, cosa succede se proviamo a modificare qualcosa che abbiamo in prestito? Prova il codice in Listing 4-6. Spoiler: non funziona!
Nome del file: src/main.rs
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world");
}
Ecco l'errore:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
--> src/main.rs:8:5
|
7 | fn change(some_string: &String) {
| ------- help: consider changing this to be a mutable reference: `&mut String`
8 | some_string.push_str(", world");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
For more information about this error, try `rustc --explain E0596`.
error: could not compile `ownership` due to previous error
Proprio come le variabili sono immutabili di default, anche i riferimenti lo sono. Non ci è permesso modificare qualcosa a cui abbiamo un riferimento.
Riferimenti Mutabili
Possiamo correggere il codice da Listing 4-6 per permetterci di modificare un valore preso in prestito con solo pochi piccoli aggiustamenti che utilizzano, invece, un riferimento mutabile:
Nome del file: src/main.rs
fn main() { let mut s = String::from("hello"); change(&mut s); } fn change(some_string: &mut String) { some_string.push_str(", world"); }
Prima cambiamo s
in mut
. Poi creiamo un riferimento mutabile con &mut s
dove chiamiamo la funzione change
, e aggiorniamo la firma della funzione per accettare un riferimento mutabile con some_string: &mut String
. Questo rende molto chiaro che la funzione change
modificherà il valore che prende in prestito.
I riferimenti mutabili hanno una grande restrizione: se hai un riferimento mutabile a un valore, non puoi avere altri riferimenti a quel valore. Questo codice che tenta di creare due riferimenti mutabili a s
fallirà:
Nome del file: src/main.rs
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
}
Ecco l'errore:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:5:14
|
4 | let r1 = &mut s;
| ------ first mutable borrow occurs here
5 | let r2 = &mut s;
| ^^^^^^ second mutable borrow occurs here
6 |
7 | println!("{}, {}", r1, r2);
| -- first borrow later used here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `ownership` due to previous error
Questo errore dice che questo codice non è valido perché non possiamo prendere in prestito s
come mutabile più di una volta alla volta. Il primo prestito mutabile è in r1
e deve durare fino a quando viene utilizzato nel println!
, ma tra la creazione di quel riferimento mutabile e il suo uso, abbiamo tentato di creare un altro riferimento mutabile in r2
che prende in prestito gli stessi dati di r1
.
La restrizione che impedisce molteplici riferimenti mutabili agli stessi dati contemporaneamente permette la mutazione ma in modo molto controllato. È qualcosa con cui i nuovi Rustaceans lottano perché la maggior parte delle lingue ti permette di mutare quando vuoi. Il vantaggio di avere questa restrizione è che Rust può prevenire le data races in fase di compilazione. Una data race è simile a una race condition e si verifica quando questi tre comportamenti si verificano:
- Due o più puntatori accedono agli stessi dati contemporaneamente.
- Almeno uno dei puntatori viene utilizzato per scrivere i dati.
- Non c'è nessun meccanismo che viene usato per sincronizzare l'accesso ai dati.
Le data races causano comportamenti indefiniti e possono essere difficili da diagnosticare e correggere quando si cerca di scovare i problemi a runtime; Rust previene questo problema rifiutandosi di compilare codice con data races!
Come sempre, possiamo usare le parentesi graffe per creare un nuovo scope, permettendo riferimenti mutabili multipli, ma non simultanei:
fn main() { let mut s = String::from("hello"); { let r1 = &mut s; } // r1 goes out of scope here, so we can make a new reference with no problems. let r2 = &mut s; }
Rust applica una regola simile per combinare riferimenti mutabili e immutabili. Questo codice produce un errore:
fn main() {
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
println!("{}, {}, and {}", r1, r2, r3);
}
Ecco l'errore:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:6:14
|
4 | let r1 = &s; // no problem
| -- immutable borrow occurs here
5 | let r2 = &s; // no problem
6 | let r3 = &mut s; // BIG PROBLEM
| ^^^^^^ mutable borrow occurs here
7 |
8 | println!("{}, {}, and {}", r1, r2, r3);
| -- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` due to previous error
Uffa! Anche non possiamo avere un riferimento mutabile mentre abbiamo uno immutabile allo stesso valore.
Gli utenti di un riferimento immutabile non si aspettano che il valore cambi improvvisamente! Tuttavia, sono permessi riferimenti immutabili multipli perché nessuno che sta solo leggendo i dati ha la capacità di influenzare la lettura dei dati di qualcun altro.
Nota che lo scope di un riferimento inizia da dove viene introdotto e continua fino all'ultima volta che quel riferimento viene utilizzato. Per esempio, questo codice compilerà perché l'ultimo utilizzo dei riferimenti immutabili, il println!
, si verifica prima che il riferimento mutabile venga introdotto:
fn main() { let mut s = String::from("hello"); let r1 = &s; // no problem let r2 = &s; // no problem println!("{} and {}", r1, r2); // variables r1 and r2 will not be used after this point let r3 = &mut s; // no problem println!("{}", r3); }
Gli scope dei riferimenti immutabili r1
e r2
terminano dopo il println!
dove vengono utilizzati per l'ultima volta, che è prima che il riferimento mutabile r3
venga creato. Questi scope non si sovrappongono, quindi questo codice è permesso: il compilatore può dire che il riferimento non viene più utilizzato in un punto prima della fine dello scope.
Anche se gli errori di borrowing possono essere frustranti a volte, ricorda che è il compilatore di Rust a indicare un potenziale bug in anticipo (in fase di compilazione piuttosto che a runtime) e a mostrarti esattamente dove si trova il problema. Poi non devi rintracciare perché i tuoi dati non sono quelli che pensavi fossero.
Riferimenti Pendenti
Nelle lingue con puntatori, è facile creare erroneamente un puntatore pendente—un puntatore che fa riferimento a una posizione in memoria che potrebbe essere stata assegnata a qualcun altro—liberando un po' di memoria mentre si conserva ancora un puntatore a quella memoria. In Rust, al contrario, il compilatore garantisce che i riferimenti non saranno mai riferimenti pendenti: se hai un riferimento a qualche dato, il compilatore assicurerà che i dati non usciranno dallo scope prima che il riferimento ai dati lo faccia.
Proviamo a creare un riferimento pendente per vedere come Rust li impedisce con un errore in fase di compilazione:
Nome del file: src/main.rs
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
Ecco l'errore:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0106]: missing lifetime specifier
--> src/main.rs:5:16
|
5 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
|
5 | fn dangle() -> &'static String {
| +++++++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `ownership` due to previous error
Questo messaggio di errore si riferisce a una funzione che non abbiamo ancora trattato: lifetimes. Discuteremo i lifetimes in dettaglio nel Capitolo 10. Ma, se ignori le parti sui lifetimes, il messaggio contiene la chiave del perché questo codice è un problema:
this function's return type contains a borrowed value, but there is no value
for it to be borrowed from
Osserviamo più da vicino cosa sta succedendo ad ogni fase del nostro codice dangle
:
Nome del file: src/main.rs
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String { // dangle returns a reference to a String
let s = String::from("hello"); // s is a new String
&s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
// Danger!
Poiché s
è creato all'interno di dangle
, quando il codice di dangle
è terminato, s
verrà deallocato. Ma abbiamo tentato di restituire un riferimento ad esso. Ciò significa che questo riferimento punterebbe a una String
non valida. Non va bene! Rust non ce lo permette.
La soluzione qui è restituire direttamente la String
:
fn main() { let string = no_dangle(); } fn no_dangle() -> String { let s = String::from("hello"); s }
Questo funziona senza problemi. Il possesso viene spostato fuori, e niente viene deallocato.
Le Regole dei Riferimenti
Riassumiamo ciò che abbiamo discusso riguardo ai riferimenti:
- In qualsiasi momento, è possibile avere o un riferimento mutabile o qualsiasi numero di riferimenti immutabili.
- I riferimenti devono essere sempre validi.
Successivamente, esamineremo un tipo diverso di riferimento: slices.
Il Tipo Slice
Le Slices ti permettono di riferirti a una sequenza contigua di elementi in una collezione piuttosto che a tutta la collezione. Una slice è un tipo di riferimento, quindi non ha ownership.
Ecco un piccolo problema di programmazione: scrivi una funzione che prende una stringa di parole separate da spazi e restituisce la prima parola che trova in quella stringa. Se la funzione non trova uno spazio nella stringa, tutta la stringa deve essere una parola, quindi deve restituire l'intera stringa.
Vediamo come scrivere la firma di questa funzione senza usare slices, per comprendere il problema che le slices risolvono:
fn first_word(s: &String) -> ?
La funzione first_word
ha un parametro &String
. Non vogliamo ownership, quindi questo va bene. Ma cosa dovremmo restituire? Non abbiamo davvero un modo per parlare di parte di una stringa. Tuttavia, potremmo restituire l'indice della fine della parola, indicato da uno spazio. Proviamoci, come mostrato nel Listing 4-7.
Filename: src/main.rs
fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() {}
Poiché dobbiamo attraversare l'elemento String
elemento per elemento e controllare se
un valore è uno spazio, convertiremo la nostra String
in un array di byte usando il
metodo as_bytes
.
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {}
Successivamente, creiamo un iteratore sull'array di byte usando il metodo iter
:
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {}
Discuteremo gli iteratori in maggior dettaglio nel Capitolo 13.
Per ora, sappi che iter
è un metodo che restituisce ogni elemento in una collezione
e che enumerate
avvolge il risultato di iter
e restituisce ciascun elemento come
parte di una tupla invece. Il primo elemento della tupla restituita da
enumerate
è l'indice, e il secondo elemento è un riferimento all'elemento.
Questo è un po' più conveniente che calcolare l'indice da soli.
Poiché il metodo enumerate
restituisce una tupla, possiamo usare i pattern per
decomporre quella tupla. Discuteremo i pattern più dettagliatamente nel Capitolo
6. Nel ciclo for
, specifichiamo un pattern che ha i
per l'indice nella tupla e &item
per il singolo byte nella tupla.
Poiché otteniamo un riferimento all'elemento da .iter().enumerate()
, usiamo
&
nel pattern.
All'interno del ciclo for
, cerchiamo il byte che rappresenta lo spazio usando
la sintassi del byte letterale. Se troviamo uno spazio, restituiamo la posizione.
Altrimenti, restituiamo la lunghezza della stringa usando s.len()
.
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {}
Ora abbiamo un modo per trovare l'indice della fine della prima parola nella
stringa, ma c'è un problema. Stiamo restituendo un usize
da solo, ma è solo
un numero significativo nel contesto di &String
. In altre parole,
poiché è un valore separato dalla String
, non c'è garanzia che sarà ancora
valido in futuro. Considera il programma nel Listing 4-8 che
usa la funzione first_word
dal Listing 4-7.
Filename: src/main.rs
fn first_word(s: &String) -> usize { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return i; } } s.len() } fn main() { let mut s = String::from("hello world"); let word = first_word(&s); // word will get the value 5 s.clear(); // this empties the String, making it equal to "" // word still has the value 5 here, but there's no more string that // we could meaningfully use the value 5 with. word is now totally invalid! }
Questo programma compila senza errori e lo farebbe anche se usassimo word
dopo aver chiamato s.clear()
. Poiché word
non è collegato affatto allo stato di s
,
word
contiene ancora il valore 5
. Potremmo usare quel valore 5
con la
variabile s
per cercare di estrarre la prima parola, ma questo sarebbe un bug
perché il contenuto di s
è cambiato da quando abbiamo salvato 5
in word
.
Doversi preoccupare dell'indice in word
che si disallinea con i dati in
s
è tedioso e soggetto a errori! La gestione di questi indici è ancora
più fragile se scriviamo una funzione second_word
. La sua firma dovrebbe assomigliare a questa:
fn second_word(s: &String) -> (usize, usize) {
Ora stiamo tracciando un indice di inizio e un indice di fine, e abbiamo ancora più valori che sono stati calcolati da dati in uno stato particolare ma non sono affatto legati a quello stato. Abbiamo tre variabili non correlate che devono essere mantenute sincronizzate.
Per fortuna, Rust ha una soluzione a questo problema: le slices di stringa.
Slices di Stringa
Una string slice è un riferimento a una parte di una String
, e appare così:
fn main() { let s = String::from("hello world"); let hello = &s[0..5]; let world = &s[6..11]; }
Piuttosto che un riferimento all'intera String
, hello
è un riferimento a una
porzione della String
, specificato nella parte aggiuntiva [0..5]
. Creiamo le slices
utilizzando un intervallo tra parentesi specificando [starting_index..ending_index]
,
dove starting_index
è la prima posizione nella slice e ending_index
è uno
in più rispetto all'ultima posizione nella slice. Internamente, la struttura dati della slice
memorizza la posizione iniziale e la lunghezza della slice, che
corrisponde a ending_index
meno starting_index
. Quindi, nel caso di let world = &s[6..11];
, world
sarebbe una slice che contiene un puntatore al
byte all'indice 6 di s
con un valore di lunghezza di 5
.
Figura 4-6 mostra questo in un diagramma.
Con la sintassi di intervallo ..
di Rust, se vuoi iniziare dall'indice 0, puoi omettere
il valore prima dei due punti. In altre parole, questi sono uguali:
#![allow(unused)] fn main() { let s = String::from("hello"); let slice = &s[0..2]; let slice = &s[..2]; }
Allo stesso modo, se la tua slice include l'ultimo byte della String
, puoi
omettere il numero finale. Questo significa che questi sono uguali:
#![allow(unused)] fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[3..len]; let slice = &s[3..]; }
Puoi anche omettere entrambi i valori per prendere una slice dell'intera stringa. Quindi questi sono uguali:
#![allow(unused)] fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[0..len]; let slice = &s[..]; }
Nota: Gli indici di intervallo delle slices devono trovarsi ai confini di caratteri validi UTF-8. Se tenti di creare una slice di stringa nel mezzo di un carattere multibyte, il tuo programma terminerà con un errore. Ai fini di introdurre le slices di stringa, stiamo assumendo solo ASCII in questa sezione; una discussione più approfondita della gestione di UTF-8 si trova nella sezione “Memorizzare Testo Codificato UTF-8 con le Stringhe” del Capitolo 8.
Con tutte queste informazioni in mente, riscriviamo first_word
per restituire una
slice. Il tipo che rappresenta “slice di stringa” è scritto come &str
:
Filename: src/main.rs
fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() {}
Otteniamo l'indice per la fine della parola allo stesso modo in cui abbiamo fatto nel Listing 4-7, cercando la prima occorrenza di uno spazio. Quando troviamo uno spazio, restituiamo una slice di stringa utilizzando l'inizio della stringa e l'indice dello spazio come indici iniziale e finale.
Ora, quando chiamiamo first_word
, otteniamo un singolo valore che è legato ai dati sottostanti. Il valore è composto da un riferimento al punto di partenza della slice e dal numero di elementi nella slice.
Restituire una slice funzionerebbe anche per una funzione second_word
:
fn second_word(s: &String) -> &str {
Ora abbiamo un'API semplice che è molto più difficile da sbagliare perché
il compilatore garantirà che i riferimenti nella String
rimangano validi. Ricorda
il bug nel programma nel Listing 4-8, quando abbiamo ottenuto l'indice per la fine della
prima parola ma poi abbiamo svuotato la stringa così il nostro indice era invalido? Quel codice era
logicamente errato ma non mostrava errori immediati. I problemi si sarebbero presentati
più tardi se avessimo continuato a usare l'indice della prima parola con una stringa svuotata.
Le slices rendono impossibile questo bug e ci fanno sapere di avere un problema con
il nostro codice molto prima. Utilizzare la versione a slice di first_word
lancerà un
errore in fase di compilazione:
Filename: src/main.rs
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // error!
println!("the first word is: {}", word);
}
Ecco l'errore del compilatore:
$ cargo run
Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable
--> src/main.rs:18:5
|
16 | let word = first_word(&s);
| -- immutable borrow occurs here
17 |
18 | s.clear(); // error!
| ^^^^^^^^^ mutable borrow occurs here
19 |
20 | println!("the first word is: {}", word);
| ---- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `ownership` due to previous error
Ricorda dalle regole del borrowing che se abbiamo un riferimento immutabile a
qualcosa, non possiamo anche prendere un riferimento mutabile. Poiché clear
deve
truncare la String
, ha bisogno di ottenere un riferimento mutabile. Il println!
dopo la chiamata a clear
usa il riferimento in word
, quindi il riferimento
immutabile deve essere ancora attivo a quel punto. Rust non permette che il riferimento mutabile in clear
e il riferimento immutabile in word
esistano
contemporaneamente, e la compilazione fallisce. Non solo Rust ha reso la nostra API più facile da usare,
ma ha anche eliminato un'intera classe di errori in fase di compilazione!
String Literals come Slices
Ricorda che abbiamo parlato di stringhe letterali memorizzate all'interno del binario. Ora che sappiamo delle slices, possiamo comprendere correttamente le stringhe letterali:
#![allow(unused)] fn main() { let s = "Hello, world!"; }
Il tipo di s
qui è &str
: è una slice che punta a quel punto specifico del binario. Questo è anche il motivo per il quale le stringhe letterali sono immutabili; &str
è un
riferimento immutabile.
Slices di Stringa come Parametri
Sapere che puoi prendere slices di letterali e valori String
ci porta
a un altro miglioramento su first_word
, ed è la sua firma:
fn first_word(s: &String) -> &str {
Un Rustacean più esperto scriverebbe la firma mostrata nel Listing 4-9
invece perché ci permette di usare la stessa funzione sia su valori &String
che &str
.
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s[..]
}
fn main() {
let my_string = String::from("hello world");
// `first_word` works on slices of `String`s, whether partial or whole
let word = first_word(&my_string[0..6]);
let word = first_word(&my_string[..]);
// `first_word` also works on references to `String`s, which are equivalent
// to whole slices of `String`s
let word = first_word(&my_string);
let my_string_literal = "hello world";
// `first_word` works on slices of string literals, whether partial or whole
let word = first_word(&my_string_literal[0..6]);
let word = first_word(&my_string_literal[..]);
// Because string literals *are* string slices already,
// this works too, without the slice syntax!
let word = first_word(my_string_literal);
}
Se abbiamo una slice di stringa, possiamo passarla direttamente. Se abbiamo una String
, possiamo passare una slice della String
o un riferimento alla String
. Questa
flessibilità sfrutta le deref coercions, una caratteristica che copriremo nella sezione
“Coercizioni Deref Implicite con Funzioni e Metodi” del Capitolo 15.
Definire una funzione per prendere una slice di stringa invece di un riferimento a una String
rende la nostra API più generale e utile senza perdere alcuna funzionalità:
Filename: src/main.rs
fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // `first_word` works on slices of `String`s, whether partial or whole let word = first_word(&my_string[0..6]); let word = first_word(&my_string[..]); // `first_word` also works on references to `String`s, which are equivalent // to whole slices of `String`s let word = first_word(&my_string); let my_string_literal = "hello world"; // `first_word` works on slices of string literals, whether partial or whole let word = first_word(&my_string_literal[0..6]); let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); }
Altre Slices
Le slices di stringa, come puoi immaginare, sono specifiche per le stringhe. Ma esiste anche un tipo di slice più generale. Considera questo array:
#![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; }
Così come potremmo voler riferirci a una parte di una stringa, potremmo voler riferirci a una parte di un array. Lo faremmo così:
#![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; let slice = &a[1..3]; assert_eq!(slice, &[2, 3]); }
Questa slice ha il tipo &[i32]
. Funziona allo stesso modo delle slices di stringa, memorizzando un riferimento al primo elemento e una lunghezza. Userai questo tipo di slice per tutti i tipi di altre collezioni. Discuteremo queste collezioni in
dettaglio quando parleremo dei vettori nel Capitolo 8.
Riepilogo
I concetti di ownership, borrowing e slices garantiscono la sicurezza della memoria nei programmi Rust in fase di compilazione. Il linguaggio Rust ti dà il controllo sull'uso della memoria allo stesso modo di altri linguaggi di programmazione di sistemi, ma avere il proprietario dei dati che automaticamente ripulisce quei dati quando il proprietario esce dallo Scope significa che non devi scrivere e debugare codice extra per ottenere questo controllo.
L'ownership influisce sul funzionamento di molte altre parti di Rust, quindi parleremo di
questi concetti ulteriormente nel resto del libro. Passiamo al
Capitolo 5 e vediamo come raggruppare pezzi di dati insieme in uno struct
.
Utilizzare le Struct per Strutturare Dati Correlati
Una struct, o struttura, è un tipo di dato personalizzato che ti permette di raggruppare e nominare insieme più valori correlati che costituiscono un gruppo significativo. Se hai familiarità con un linguaggio orientato agli oggetti, una struct è come gli attributi di dati di un oggetto. In questo capitolo, confronteremo e contrasteremo le tuple con le struct per costruire su ciò che già sai e dimostrare quando le struct sono un modo migliore per raggruppare i dati.
Dimostreremo come definire e istanziare le struct. Discuteremo come definire funzioni associate, in particolare il tipo di funzioni associate chiamate methods, per specificare il comportamento associato a un tipo di struct. Le Struct e gli enums (discussi nel Capitolo 6) sono i mattoni per creare nuovi tipi nel dominio del tuo programma per sfruttare appieno il controllo dei tipi durante la compilazione di Rust.
Definizione e istanziazione di Struct
Le Struct sono simili ai tuple, discussi nella sezione “Il Tipo Tuple”, in quanto entrambi contengono più valori correlati. Come nei tuple, i componenti di una struct possono essere di tipi diversi. A differenza dei tuple, in una struct si assegna un nome a ciascun elemento di dati, quindi è chiaro cosa significano i valori. L'aggiunta di questi nomi rende le struct più flessibili dei tuple: non è necessario fare affidamento sull'ordine dei dati per specificare o accedere ai valori di un'istanza.
Per definire una struct, inseriamo la parola chiave struct
e nominiamo l'intera
struct. Il nome di una struct dovrebbe descrivere l'importanza dei dati che vengono
raggruppati. Quindi, tra parentesi graffe, definiamo i nomi e i tipi dei dati, che
chiamiamo campi. Ad esempio, Elenco 5-1 mostra una struct che memorizza informazioni
su un account utente.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() {}
Per utilizzare una struct dopo averla definita, creiamo un' istanza di quella struct
specificando valori concreti per ciascuno dei campi. Creiamo un'istanza dichiarando
il nome della struct e poi aggiungendo parentesi graffe contenenti coppie chiave: valore,
dove le chiavi sono i nomi dei campi e i valori sono i dati che vogliamo memorizzare in quei
campi. Non è necessario specificare i campi nello stesso ordine in cui sono stati dichiarati
nella struct. In altre parole, la definizione di struct è come un modello generale per il tipo,
e le istanze compilano quel modello con dati particolari per creare valori del tipo. Ad esempio,
possiamo dichiarare un utente specifico come mostrato nell'Elenco 5-2.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { let user1 = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; }
Per ottenere un valore specifico da una struct, utilizziamo la notazione a punti. Ad esempio,
per accedere all'indirizzo email di questo utente, usiamo user1.email
. Se l'istanza è mutable,
possiamo cambiare un valore utilizzando la notazione a punti e assegnando a un campo particolare.
L'Elenco 5-3 mostra come cambiare il valore nel campo email
di un'istanza mutable di User
.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { let mut user1 = User { active: true, username: String::from("someusername123"), email: String::from("someone@example.com"), sign_in_count: 1, }; user1.email = String::from("anotheremail@example.com"); }
Nota che l'intera istanza deve essere mutable; Rust non permette di contrassegnare solo alcuni campi come mutable. Come con qualsiasi espressione, possiamo costruire una nuova istanza della struct come ultima espressione nel corpo della funzione per restituire implicitamente quella nuova istanza.
L'Elenco 5-4 mostra una funzione build_user
che restituisce un'istanza User
con l'email e
il nome utente forniti. Il campo active
ottiene il valore true
, e il campo sign_in_count
ottiene un valore di 1
.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn build_user(email: String, username: String) -> User { User { active: true, username: username, email: email, sign_in_count: 1, } } fn main() { let user1 = build_user( String::from("someone@example.com"), String::from("someusername123"), ); }
Ha senso chiamare i parametri della funzione con lo stesso nome dei campi della struct, ma
dover ripetere i nomi dei campi email
e username
e le variabili è un po' tedioso. Se
la struct avesse più campi, ripetere ogni nome diventerebbe ancora più fastidioso. Per fortuna,
esiste una scorciatoia comoda!
Utilizzo della scorciatoia per l'inizializzazione dei campi
Poiché i nomi dei parametri e i nomi dei campi della struct sono esattamente uguali in
l'Elenco 5-4, possiamo usare la sintassi scorciatoia per l'inizializzazione dei campi per
riscrivere build_user
in modo che si comporti esattamente allo stesso modo ma senza la ripetizione
di username
e email
, come mostrato nell'Elenco 5-5.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn build_user(email: String, username: String) -> User { User { active: true, username, email, sign_in_count: 1, } } fn main() { let user1 = build_user( String::from("someone@example.com"), String::from("someusername123"), ); }
Qui, stiamo creando una nuova istanza della struct User
, che ha un campo denominato email
.
Vogliamo impostare il valore del campo email
al valore del parametro email
della funzione
build_user
. Poiché il campo email
e il parametro email
hanno lo stesso nome, dobbiamo
scrivere solo email
invece di email: email
.
Creazione di istanze da altre istanze con la sintassi di aggiornamento delle struct
È spesso utile creare una nuova istanza di una struct che include la maggior parte dei valori da un'altra istanza, ma ne cambia alcuni. È possibile farlo utilizzando la sintassi di aggiornamento delle struct.
Per prima cosa, nell'Elenco 5-6 mostriamo come creare una nuova istanza User
in user2
regolarmente, senza la sintassi di aggiornamento. Impostiamo un nuovo valore per email
ma
usiamo gli stessi valori di user1
che abbiamo creato nell'Elenco 5-2.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { // --snip-- let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; let user2 = User { active: user1.active, username: user1.username, email: String::from("another@example.com"), sign_in_count: user1.sign_in_count, }; }
Utilizzando la sintassi di aggiornamento delle struct, possiamo ottenere lo stesso effetto con
meno codice, come mostrato nell'Elenco 5-7. La sintassi ..
specifica che i campi rimanenti
non impostati esplicitamente devono avere lo stesso valore dei campi nell'istanza data.
Nome del file: src/main.rs
struct User { active: bool, username: String, email: String, sign_in_count: u64, } fn main() { // --snip-- let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; let user2 = User { email: String::from("another@example.com"), ..user1 }; }
Il codice nell'Elenco 5-7 crea anche un'istanza in user2
che ha un valore diverso per email
ma ha gli stessi valori per i campi username
, active
e sign_in_count
da user1
. Il ..user1
deve venire per ultimo per specificare che i campi rimanenti dovrebbero ottenere i loro valori dai
campi corrispondenti in user1
, ma possiamo scegliere di specificare valori per quanti campi
vogliamo in qualsiasi ordine, indipendentemente dall'ordine dei campi nella definizione della struct.
Nota che la sintassi di aggiornamento delle struct utilizza =
come un'assegnazione; questo
perché sposta i dati, proprio come abbiamo visto nella sezione “Variabili e Dati che Interagiscono
con il Movimento”. In questo esempio, non possiamo più utilizzare user1
come
un tutto dopo aver creato user2
perché il String
nel campo username
di user1
è stato
spostato in user2
. Se avessimo dato a user2
nuovi valori String
sia per email
che per
username
, e quindi avessimo utilizzato solo i valori active
e sign_in_count
da user1
,
allora user1
sarebbe ancora valido dopo aver creato user2
. Sia active
che sign_in_count
sono tipi che implementano il trait Copy
, quindi il comportamento discusso nella sezione
“Dati Solo nel Pila: Copy” si applicherebbe.
Utilizzo di Struct a Tupla senza Campi Nominati per Creare Tipi Diversi
Rust supporta anche struct che sembrano simili ai tuple, chiamati struct a tupla. Le struct a tupla hanno il significato aggiunto fornito dal nome della struct ma non hanno nomi associati ai loro campi; piuttosto, hanno solo i tipi dei campi. Le struct a tupla sono utili quando si desidera dare all'intero tuple un nome e rendere il tuple un tipo diverso rispetto ad altri tuple, e quando assegnare un nome a ciascun campo come in una struct regolare sarebbe verboso o ridondante.
Per definire una struct a tupla, inizia con la parola chiave struct
e il nome della struct
seguiti dai tipi nel tuple. Ad esempio, qui definiamo e utilizziamo due struct a tupla chiamate
Color
e Point
:
Nome del file: src/main.rs
struct Color(i32, i32, i32); struct Point(i32, i32, i32); fn main() { let black = Color(0, 0, 0); let origin = Point(0, 0, 0); }
Nota che i valori black
e origin
sono tipi diversi perché sono istanze di struct a tupla
diverse. Ogni struct che definisci è il proprio tipo, anche se i campi all'interno della struct
potrebbero avere gli stessi tipi. Ad esempio, una funzione che prende un parametro di tipo Color
non può prendere un Point
come argomento, anche se entrambi i tipi sono costituiti da tre valori i32
.
Altrimenti, le istanze di struct a tupla sono simili ai tuple in quanto è possibile destrutturarle
nei loro singoli componenti, e si può utilizzare un .
seguito dall'indice per accedere a un valore
individuale.
Struct a Unità senza Campi
È possibile definire struct che non hanno campi! Questi sono chiamati struct a unità perché si
comportano in modo simile a ()
, il tipo unità che abbiamo menzionato nella sezione
“Il Tipo Tuple”. Le struct a unità possono essere utili quando è necessario
implementare un trait su qualche tipo ma non si hanno dati che si desidera memorizzare nel tipo stesso.
Discuteremo dei trait nel Capitolo 10. Ecco un esempio di dichiarazione e istanziazione di una struct
a unità chiamata AlwaysEqual
:
Nome del file: src/main.rs
struct AlwaysEqual; fn main() { let subject = AlwaysEqual; }
Per definire AlwaysEqual
, utilizziamo la parola chiave struct
, il nome che desideriamo,
e poi un punto e virgola. Nessun bisogno di parentesi graffe o parentesi! Poi possiamo ottenere
un'istanza di AlwaysEqual
nella variabile subject
in un modo simile: utilizzando il nome
che abbiamo definito, senza alcuna parentesi graffe o parentesi. Immagina che più tardi implementeremo
un comportamento per questo tipo tale che ogni istanza di AlwaysEqual
sia sempre uguale a ogni
istanza di qualsiasi altro tipo, magari per avere un risultato noto per scopi di test. Non avremmo
bisogno di alcun dato per implementare quel comportamento! Vedrai nel Capitolo 10 come definire trait
e implementarli su qualsiasi tipo, incluse le struct a unità.
Proprietà dei Dati nelle Struct
Nella definizione di
User
nell'Elenco 5-1, abbiamo usato il tipoString
di proprietà piuttosto che il tipo di slice di stringa&str
. Questa è una scelta deliberata perché vogliamo che ciascuna istanza di questa struct sia proprietaria di tutti i suoi dati e che quei dati siano validi per tutto il tempo in cui la struct è valida.È anche possibile che le struct memorizzino riferimenti a dati posseduti da qualcos'altro, ma per farlo è necessario utilizzare le lifetime, una funzione di Rust che discuteremo nel Capitolo 10. Le lifetime assicurano che i dati riferiti da una struct siano validi per tutto il tempo in cui la struct è valida. Supponiamo che tu provi a memorizzare un riferimento in una struct senza specificare le lifetime, come segue; questo non funzionerà:
Nome del file: src/main.rs
struct User { active: bool, username: &str, email: &str, sign_in_count: u64, } fn main() { let user1 = User { active: true, username: "someusername123", email: "someone@example.com", sign_in_count: 1, }; }
Il compilatore si lamenterà perché ha bisogno di specificatori di lifetime:
$ cargo run Compiling structs v0.1.0 (file:///projects/structs) error[E0106]: missing lifetime specifier --> src/main.rs:3:15 | 3 | username: &str, | ^ expected named lifetime parameter | help: consider introducing a named lifetime parameter | 1 ~ struct User<'a> { 2 | active: bool, 3 ~ username: &'a str, | error[E0106]: missing lifetime specifier --> src/main.rs:4:12 | 4 | email: &str, | ^ expected named lifetime parameter | help: consider introducing a named lifetime parameter | 1 ~ struct User<'a> { 2 | active: bool, 3 | username: &str, 4 ~ email: &'a str, | For more information about this error, try `rustc --explain E0106`. error: could not compile `structs` (bin "structs") due to 2 previous errors
Nel Capitolo 10, discuteremo come risolvere questi errori in modo che tu possa memorizzare riferimenti nelle struct, ma per ora, risolveremo errori come questi usando tipi di proprietà come
String
invece di riferimenti come&str
.
Un Programma Esempio Usando Struct
Per capire quando potremmo voler usare Struct, scriviamo un programma che calcola l'area di un rettangolo. Inizieremo usando variabili singole e poi rifattoreremo il programma fino a usare Struct.
Creiamo un nuovo progetto binario con Cargo chiamato rectangles che prenderà la larghezza e l'altezza di un rettangolo specificato in pixel e calcolerà l'area del rettangolo. Il Listing 5-8 mostra un breve programma con un modo per fare esattamente ciò nel file src/main.rs del nostro progetto.
Nome del file: src/main.rs
fn main() { let width1 = 30; let height1 = 50; println!( "The area of the rectangle is {} square pixels.", area(width1, height1) ); } fn area(width: u32, height: u32) -> u32 { width * height }
Ora esegui questo programma usando cargo run
:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished dev [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/rectangles`
The area of the rectangle is 1500 square pixels.
Questo codice riesce a calcolare l'area del rettangolo chiamando la
funzione area
con ciascuna dimensione, ma possiamo fare di più per rendere questo codice chiaro
e leggibile.
Il problema con questo codice è evidente nella firma della funzione area
:
fn main() {
let width1 = 30;
let height1 = 50;
println!(
"The area of the rectangle is {} square pixels.",
area(width1, height1)
);
}
fn area(width: u32, height: u32) -> u32 {
width * height
}
La funzione area
dovrebbe calcolare l'area di un solo rettangolo, ma la
funzione che abbiamo scritto ha due parametri, e non è chiaro da nessuna parte nel nostro
programma che i parametri siano correlati. Sarebbe più leggibile e più
gestibile raggruppare larghezza e altezza insieme. Abbiamo già discusso un modo
per farlo nella sezione "Il Tipo Tuple" del Capitolo 3: usando le tuple.
Rifattorizzare con Tuple
Il Listing 5-9 mostra un'altra versione del nostro programma che utilizza le tuple.
Nome del file: src/main.rs
fn main() { let rect1 = (30, 50); println!( "The area of the rectangle is {} square pixels.", area(rect1) ); } fn area(dimensions: (u32, u32)) -> u32 { dimensions.0 * dimensions.1 }
In un certo senso, questo programma è migliore. Le tuple ci permettono di aggiungere un po' di struttura, e ora stiamo passando solo un argomento. Ma in un altro modo, questa versione è meno chiara: le tuple non nominano i loro elementi, quindi dobbiamo indicizzare le parti della tupla, rendendo il nostro calcolo meno ovvio.
Confondere la larghezza e l'altezza non importerebbe per il calcolo dell'area, ma se
vogliamo disegnare il rettangolo sullo schermo, importerebbe! Dovremmo tener a mente che width
è
l'indice di tupla 0
e height
è l'indice di tupla 1
. Questo sarebbe ancora più difficile per qualcun altro da capire e tenere a mente se usasse il nostro codice. Poiché non abbiamo trasmesso il significato dei nostri dati nel codice, è ora più facile introdurre errori.
Rifattorizzare con Struct: Aggiungere Più Significato
Usiamo Struct per aggiungere significato etichettando i dati. Possiamo trasformare la tupla che stiamo usando in una Struct con un nome per l'intero così come nomi per le parti, come mostrato nel Listing 5-10.
Nome del file: src/main.rs
struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!( "The area of the rectangle is {} square pixels.", area(&rect1) ); } fn area(rectangle: &Rectangle) -> u32 { rectangle.width * rectangle.height }
Qui abbiamo definito una Struct e l'abbiamo chiamata Rectangle
. Dentro le parentesi graffe,
abbiamo definito i campi come width
e height
, entrambi di tipo u32
. Poi, in main
, abbiamo creato una particolare istanza di Rectangle
che ha una larghezza di 30
e un'altezza di 50
.
La nostra funzione area
è ora definita con un parametro, che abbiamo chiamato
rectangle
, il cui tipo è un prestito immutabile di una istanza di Rectangle
.
Come menzionato nel Capitolo 4, vogliamo prendere in prestito la Struct piuttosto che prendere proprietà di essa. In questo modo, main
mantiene la sua proprietà e può continuare a usare rect1
, il che è il motivo per cui usiamo &
nella firma della funzione e
dove chiamiamo la funzione.
La funzione area
accede ai campi width
e height
della
istanza Rectangle
(nota che accedere ai campi di una istanza di Struct presa in prestito non
sposta i valori dei campi, motivo per cui spesso si vedono prestiti di Struct). La nostra
firma della funzione per area
ora dice esattamente cosa intendiamo: calcolare l'area
di Rectangle
, usando i suoi campi width
e height
. Questo comunica che
la larghezza e l'altezza sono correlate tra loro, e dà nomi descrittivi ai
valori piuttosto che usare i valori di indice della tupla 0
e 1
. È una vittoria
per la chiarezza.
Aggiungere Funzionalità Utili con i Trait Derivati
Sarebbe utile poter stampare un'istanza di Rectangle
mentre stiamo
debuggando il nostro programma e vedere i valori di tutti i suoi campi. Il Listing 5-11 cerca
di usare la macro println!
come abbiamo fatto nei
capitoli precedenti. Questo però non funzionerà.
Nome del file: src/main.rs
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
println!("rect1 is {}", rect1);
}
Quando compiliamo questo codice, otteniamo un errore con questo messaggio centrale:
error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`
La macro println!
può fare molti tipi di formattazione, e per impostazione predefinita, le parentesi
graffe indicano a println!
di usare formattazione nota come Display
: output previsto
per il consumo diretto dell'utente finale. I tipi primitivi che abbiamo visto finora
implementano Display
per impostazione predefinita perché c'è solo un modo in cui si vorrebbe
mostrare un 1
o qualsiasi altro tipo primitivo a un utente. Ma con le Struct, il modo in cui
println!
dovrebbe formattare l'output è meno chiaro perché ci sono più
possibilità di visualizzazione: vuoi virgole o no? Vuoi stampare le parentesi
graffe? Dovrebbero essere mostrati tutti i campi? A causa di questa ambiguità, Rust
non cerca di indovinare cosa vogliamo, e le Struct non hanno un'implementazione
fornita di Display
da usare con println!
e il segnaposto {}
.
Se continuiamo a leggere gli errori, troveremo questa nota utile:
= help: the trait `std::fmt::Display` is not implemented for `Rectangle`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
Proviamolo! La chiamata alla macro println!
sembrerà ora println!("rect1 è {rect1:?}");
. Mettere lo specificatore :?
dentro le parentesi graffe indica a
println!
che vogliamo usare un formato di output chiamato Debug
. Il Trait Debug
ci consente di stampare la nostra Struct in un modo utile per gli sviluppatori, così possiamo
vedere il suo valore mentre stiamo debugando il nostro codice.
Compila il codice con questo cambiamento. Maledizione! Riceviamo ancora un errore:
error[E0277]: `Rectangle` doesn't implement `Debug`
Ma ancora, il compilatore ci dà una nota utile:
= help: the trait `Debug` is not implemented for `Rectangle`
= note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`
Rust inclus la funzionalità per stampare informazioni di debugging, ma dobbiamo
optare esplicitamente per rendere disponibile quella funzionalità per la nostra Struct.
Per farlo, aggiungiamo l'attributo esterno #[derive(Debug)]
appena prima della
definizione della Struct, come mostrato nel Listing 5-12.
Nome del file: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!("rect1 is {:?}", rect1); }
Ora quando eseguiamo il programma, non otterremo errori, e vedremo il seguente output:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished dev [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/rectangles`
rect1 is Rectangle { width: 30, height: 50 }
Bello! Non è l'output più bello, ma mostra i valori di tutti i campi
di questa istanza, il che sarebbe sicuramente utile durante il debugging. Quando abbiamo
Struct più grandi, è utile avere un output un po' più facile da leggere; in
questi casi, possiamo usare {:#?}
invece di {:?}
nella stringa di println!
. In
questo esempio, usando lo stile {:#?}
si otterrà il seguente output:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished dev [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/rectangles`
rect1 is Rectangle {
width: 30,
height: 50,
}
Un altro modo per stampare un valore usando il formato Debug
è usare la macro dbg!
, che prende proprietà di un'espressione (a differenza di println!
, che prende un riferimento), stampa il file e il numero di riga dove quella chiamata alla macro dbg!
si verifica nel codice insieme al valore risultante
di quella espressione, e restituisce la proprietà del valore.
Nota: Chiamare la macro
dbg!
stampa allo stream del console error standard (stderr), al contrario diprintln!
, che stampa allo stream del console output standard (stdout). Parleremo di più distderr
estdout
nella sezione "Scrittura di Messaggi di Errore su Error Standard invece di Output Standard" nel Capitolo 12.
Ecco un esempio dove siamo interessati al valore che viene assegnato al campo width
, così come il valore della intera Struct in rect1
:
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let scale = 2; let rect1 = Rectangle { width: dbg!(30 * scale), height: 50, }; dbg!(&rect1); }
Possiamo mettere dbg!
intorno all'espressione 30 * scale
e, poiché dbg!
restituisce la proprietà del valore dell'espressione, il campo width
otterrà lo
stesso valore come se non avessimo la chiamata dbg!
lì. Non vogliamo che dbg!
prenda la proprietà di rect1
, quindi usiamo un riferimento a rect1
nella chiamata successiva.
Ecco come appare l'output di questo esempio:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished dev [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/rectangles`
[src/main.rs:10] 30 * scale = 60
[src/main.rs:14] &rect1 = Rectangle {
width: 60,
height: 50,
}
Possiamo vedere che il primo pezzo di output viene da src/main.rs linea 10 dove stiamo
debuggando l'espressione 30 * scale
, e il suo valore risultante è 60
(la formattazione Debug
implementata per gli interi è stampare solo il loro valore). La chiamata a dbg!
sulla linea 14 di src/main.rs stampa il valore di &rect1
, che è
la Struct Rectangle
. Questo output usa la formattazione Debug
"pretty" del tipo
Rectangle
. La macro dbg!
può essere molto utile quando stai cercando di
capire cosa sta facendo il tuo codice!
Oltre al Trait Debug
, Rust ha fornito diversi Traits da usare con l'attributo derive
che possono aggiungere comportamento utile ai nostri tipi personalizzati. Quei Traits e i loro comportamenti sono elencati in Appendice C. Tratteremo come implementare questi Traits con comportamento personalizzato così come come creare i tuoi Traits nel Capitolo 10. Ci sono anche molti attributi diversi da derive
; per ulteriori informazioni, consulta la sezione "Attributi" del Riferimento Rust.
La nostra funzione area
è molto specifica: calcola solo l'area dei rettangoli.
Sarebbe utile legare questo comportamento più strettamente alla nostra Struct Rectangle
perché non funzionerà con nessun altro tipo. Vediamo come possiamo continuare a
refattorizzare questo codice trasformando la funzione area
in un metodo area
definito sul nostro tipo Rectangle
.
Sintassi del Metodo
I metodi sono simili alle funzioni: li dichiariamo con la parola chiave fn
e un nome, possono avere parametri e un valore di ritorno, e contengono del codice che viene eseguito quando il metodo viene chiamato da qualche altra parte. A differenza delle funzioni, i metodi sono definiti nel contesto di una struct (o un enum o un trait object, che copriremo rispettivamente nel Capitolo 6 e Capitolo 17), e il loro primo parametro è sempre self
, che rappresenta l'istanza della struct su cui il metodo viene chiamato.
Definire Metodi
Cambiamo la funzione area
che ha un'istanza di Rectangle
come parametro e invece facciamo un metodo area
definito sulla struct Rectangle
, come mostrato nel Listing 5-13.
Nome del file: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; println!( "The area of the rectangle is {} square pixels.", rect1.area() ); }
Per definire la funzione nel contesto di Rectangle
, iniziamo un blocco impl
(implementazione) per Rectangle
. Tutto ciò che si trova all'interno di questo blocco impl
sarà associato al tipo Rectangle
. Poi spostiamo la funzione area
all'interno delle parentesi graffe dell'impl
e cambiamo il primo (e in questo caso, unico) parametro in self
nella firma e ovunque all'interno del corpo. In main
, dove abbiamo chiamato la funzione area
e passato rect1
come argomento, possiamo invece usare la sintassi del metodo per chiamare il metodo area
sulla nostra istanza di Rectangle
. La sintassi del metodo va dopo un'istanza: aggiungiamo un punto seguito dal nome del metodo, parentesi tonde e qualsiasi argomento.
Nella firma per area
, usiamo &self
invece di rectangle: &Rectangle
. Il &self
è in realtà una forma abbreviata per self: &Self
. All'interno di un blocco impl
, il tipo Self
è un alias per il tipo per cui è il blocco impl
. I metodi devono avere un parametro chiamato self
di tipo Self
come loro primo parametro, quindi Rust permette di abbreviare questo con solo il nome self
nella prima posizione del parametro. Notare che dobbiamo ancora usare il &
davanti al self
abbreviato per indicare che questo metodo prende in prestito l'istanza di Self
, proprio come abbiamo fatto in rectangle: &Rectangle
. I metodi possono prendere possesso di self
, prendere in prestito self
immutabilmente, come abbiamo fatto qui, o prendere in prestito self
mutabilmente, proprio come possono fare con qualsiasi altro parametro.
Abbiamo scelto &self
qui per lo stesso motivo per cui abbiamo usato &Rectangle
nella versione della funzione: non vogliamo prendere possesso, e vogliamo solo leggere i dati nella struct, non scriverci. Se volessimo cambiare l'istanza su cui abbiamo chiamato il metodo come parte di ciò che il metodo fa, useremmo &mut self
come primo parametro. Avere un metodo che prende possesso dell'istanza usando solo self
come primo parametro è raro; questa tecnica è di solito usata quando il metodo trasforma self
in qualcos'altro e si vuole prevenire l'utente dal usare l'istanza originale dopo la trasformazione.
Il motivo principale per usare i metodi anziché le funzioni, oltre a fornire una sintassi del metodo e non dover ripetere il tipo di self
in ogni firma del metodo, è per l'organizzazione. Abbiamo messo tutte le cose che possiamo fare con un'istanza di un tipo in un unico blocco impl
anziché far cercare agli utenti futuri del nostro codice le capacità di Rectangle
in vari posti nella libreria che forniamo.
Notare che possiamo scegliere di dare a un metodo lo stesso nome di uno dei campi della struct. Ad esempio, possiamo definire un metodo su Rectangle
che è anche chiamato width
:
Nome del file: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn width(&self) -> bool { self.width > 0 } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; if rect1.width() { println!("The rectangle has a nonzero width; it is {}", rect1.width); } }
Qui, scegliamo di fare in modo che il metodo width
ritorni true
se il valore nel campo width
dell'istanza è maggiore di 0
e false
se il valore è 0
: possiamo usare un campo all'interno di un metodo con lo stesso nome per qualsiasi scopo. In main
, quando seguiamo rect1.width
con delle parentesi tonde, Rust sa che intendiamo il metodo width
. Quando non usiamo le parentesi tonde, Rust sa che intendiamo il campo width
.
Spesso, ma non sempre, quando diamo a un metodo lo stesso nome di un campo vogliamo che solo ritorni il valore nel campo e non faccia nient'altro. Metodi come questi sono chiamati getter, e Rust non li implementa automaticamente per i campi della struct come fanno alcuni altri linguaggi. I getter sono utili perché puoi rendere il campo privato ma il metodo pubblico, e quindi abilitare l'accesso in sola lettura a quel campo come parte dell'API pubblica del tipo. Discuteremo cosa significano pubblico e privato e come designare un campo o un metodo come pubblico o privato nel Capitolo 7.
Dov'è l'Operatore
->
?In C e C++, si usano due operatori diversi per chiamare metodi: si usa
.
se si chiama un metodo direttamente sull'oggetto e->
se si chiama il metodo su un puntatore all'oggetto e si ha bisogno di dereferenziare il puntatore prima. In altre parole, seobject
è un puntatore,object->something()
è simile a(*object).something()
.Rust non ha un equivalente dell'operatore
->
; invece, Rust ha una funzionalità chiamata riferiemento e dereferimento automatico. Chiamare metodi è uno dei pochi posti in Rust che ha questo comportamento.Ecco come funziona: quando chiami un metodo con
object.something()
, Rust aggiunge automaticamente&
,&mut
, o*
affinchéobject
corrisponda alla firma del metodo. In altre parole, i seguenti sono equivalenti:#![allow(unused)] fn main() { #[derive(Debug,Copy,Clone)] struct Point { x: f64, y: f64, } impl Point { fn distance(&self, other: &Point) -> f64 { let x_squared = f64::powi(other.x - self.x, 2); let y_squared = f64::powi(other.y - self.y, 2); f64::sqrt(x_squared + y_squared) } } let p1 = Point { x: 0.0, y: 0.0 }; let p2 = Point { x: 5.0, y: 6.5 }; p1.distance(&p2); (&p1).distance(&p2); }
Il primo sembra molto più pulito. Questo comportamento di riferimento automatico funziona perché i metodi hanno un chiaro ricevitore, il tipo di
self
. Dato il ricevitore e il nome di un metodo, Rust può capire in modo definitivo se il metodo sta leggendo (&self
), mutando (&mut self
), o consumando (self
). Il fatto che Rust renda implicito il trasferimento di proprietà per i ricevitori di metodo è una grande parte di ciò che rende la proprietà ergonomica in pratica.
Metodi con Più Parametri
Pratichiamo l'uso dei metodi implementando un secondo metodo sulla struct Rectangle
. Questa volta vogliamo che un'istanza di Rectangle
prenda un'altra istanza di Rectangle
e ritorni true
se la seconda Rectangle
può essere contenuta completamente all'interno di self
(la prima Rectangle
); altrimenti, dovrebbe ritornare false
. Cioè, una volta che abbiamo definito il metodo can_hold
, vogliamo essere in grado di scrivere il programma mostrato nel Listing 5-14.
Nome del file: src/main.rs
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
L'output previsto sarebbe simile al seguente perché entrambe le dimensioni di rect2
sono più piccole delle dimensioni di rect1
, ma rect3
è più largo di rect1
:
Can rect1 hold rect2? true
Can rect1 hold rect3? false
Sappiamo di voler definire un metodo, quindi sarà all'interno del blocco impl Rectangle
. Il nome del metodo sarà can_hold
e prenderà in prestito immutabilmente un'altra Rectangle
come parametro. Possiamo dire quale sarà il tipo del parametro guardando il codice che chiama il metodo: rect1.can_hold(&rect2)
passa &rect2
, che è un prestito immutabile di rect2
, un'istanza di Rectangle
. Questo ha senso perché dobbiamo solo leggere rect2
(anziché scriverci, cosa che significherebbe che avremmo bisogno di un prestito mutabile), e vogliamo che main
mantenga la proprietà di rect2
così possiamo usarlo di nuovo dopo aver chiamato il metodo can_hold
. Il valore di ritorno di can_hold
sarà un valore booleano, e l'implementazione controllerà se la larghezza e l'altezza di self
sono maggiori della larghezza e dell'altezza dell'altra Rectangle
, rispettivamente. Aggiungiamo il nuovo metodo can_hold
al blocco impl
dal Listing 5-13, mostrato nel Listing 5-15.
Nome del file: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); }
Quando eseguiamo questo codice con la funzione main
nel Listing 5-14, otterremo il nostro output desiderato. I metodi possono avere diversi parametri che aggiungiamo alla firma dopo il parametro self
, e quei parametri funziano proprio come i parametri nelle funzioni.
Funzioni Associate
Tutte le funzioni definite all'interno di un blocco impl
sono chiamate funzioni associate perché sono associate al tipo denominato dopo l'impl
. Possiamo definire funzioni associate che non hanno self
come loro primo parametro (e quindi non sono metodi) perché non necessitano di un'istanza del tipo con cui lavorare. Abbiamo già usato una funzione di questo tipo: la funzione String::from
che è definita sul tipo String
.
Le funzioni associate che non sono metodi sono spesso utilizzate per costruttori che ritorneranno una nuova istanza della struct. Questi sono spesso chiamati new
, ma new
non è un nome speciale e non è integrato nel linguaggio. Per esempio, potremmo scegliere di fornire una funzione associata chiamata square
che avrebbe un parametro di dimensione e userebbe quello sia come larghezza che come altezza, rendendo così più facile creare un Rectangle
quadrato piuttosto che dover specificare lo stesso valore due volte:
Nome del file: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn square(size: u32) -> Self { Self { width: size, height: size, } } } fn main() { let sq = Rectangle::square(3); }
Le parole chiave Self
nel tipo di ritorno e nel corpo della funzione sono alias per il tipo che appare dopo la parola chiave impl
, che in questo caso è Rectangle
.
Per chiamare questa funzione associata, usiamo la sintassi ::
con il nome della struct; let sq = Rectangle::square(3);
è un esempio. Questa funzione è nello spazio dei nomi della struct: la sintassi ::
è utilizzata sia per le funzioni associate che per gli spazi dei nomi creati dai moduli. Discuteremo i moduli nel Capitolo 7.
Molteplici Blocchi impl
Ogni struct è autorizzata ad avere molteplici blocchi impl
. Ad esempio, il Listing 5-15 è equivalente al codice mostrato nel Listing 5-16, che ha ogni metodo nel proprio blocco impl
.
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } } impl Rectangle { fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; let rect3 = Rectangle { width: 60, height: 45, }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); }
Non c'è nessun motivo per separare questi metodi in molteplici blocchi impl
qui, ma questa è una sintassi valida. Vedremo un caso in cui molteplici blocchi impl
sono utili nel Capitolo 10, dove discuteremo i tipi generici e i trait.
Sommario
Le struct ti permettono di creare tipi personalizzati significativi per il tuo dominio. Usando le struct, puoi mantenere pezzi di dati associati tra di loro e nominare ogni pezzo per rendere il tuo codice chiaro. Nei blocchi impl
, puoi definire funzioni che sono associate al tuo tipo, e i metodi sono un tipo di funzione associata che ti permette di specificare il comportamento che le istanze delle tue struct hanno.
Ma le struct non sono l'unico modo in cui puoi creare tipi personalizzati: passiamo alla caratteristica degli enum di Rust per aggiungere un altro strumento al tuo toolbox.
Enum e Pattern Matching
In questo capitolo, esamineremo le enumerazioni, anche note come enum. Gli enum permettono di definire un tipo enumerando le sue possibili varianti. Prima definiremo e utilizzeremo un enum per mostrare come un enum possa codificare significato insieme ai dati. Successivamente, esploreremo un enum particolarmente utile, chiamato Option
, che esprime che un valore può essere qualcosa o nulla. Poi vedremo come il pattern matching nell'espressione match
renda facile eseguire codice diverso per valori diversi di un enum. Infine, tratteremo come il costrutto if let
sia un altro idio ma conveniente e conciso disponibile per gestire gli enum nel tuo codice.
Definire un Enum
Dove le struct ti offrono un modo per raggruppare campi e dati correlati, come un Rettangolo
con la sua larghezza
e altezza
, gli enum ti danno un modo di dire che un valore è uno di un possibile insieme di valori. Ad esempio, potremmo voler dire che Rettangolo
è una di una serie di forme possibili che include anche Cerchio
e Triangolo
. Per fare questo, Rust ci permette di codificare queste possibilità come un enum.
Vediamo una situazione che potremmo voler esprimere nel codice e capire perché gli enum sono utili e più appropriati delle struct in questo caso. Supponiamo di dover lavorare con indirizzi IP. Al momento, due standard principali sono utilizzati per gli indirizzi IP: versione quattro e versione sei. Poiché queste sono le uniche possibilità che il nostro programma incontrerà per un indirizzo IP, possiamo enumerare tutte le varianti possibili, che è da dove deriva il nome di enumerazione.
Qualsiasi indirizzo IP può essere sia un indirizzo di versione quattro che un indirizzo di versione sei, ma non entrambi contemporaneamente. Questa proprietà degli indirizzi IP rende appropriata la struttura dati enum poiché un valore enum può essere solo una delle sue varianti. Sia gli indirizzi di versione quattro che quelli di versione sei sono comunque fondamentalmente indirizzi IP, quindi dovrebbero essere trattati come lo stesso tipo quando il codice gestisce situazioni che si applicano a qualsiasi tipo di indirizzo IP.
Possiamo esprimere questo concetto nel codice definendo un'enumerazione IpAddrKind
e elencando i tipi possibili di un indirizzo IP, V4
e V6
. Queste sono le varianti dell'enum:
enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {}
IpAddrKind
è ora un tipo di dati personalizzato che possiamo usare altrove nel nostro codice.
Valori Enum
Possiamo creare istanze di ciascuna delle due varianti di IpAddrKind
in questo modo:
enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {}
Nota che le varianti dell'enum sono spazialmente nominate sotto il suo identificatore e usiamo un doppio due punti per separare i due. Questo è utile perché ora entrambi i valori IpAddrKind::V4
e IpAddrKind::V6
sono dello stesso tipo: IpAddrKind
. Possiamo quindi, ad esempio, definire una funzione che accetta qualsiasi IpAddrKind
:
enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {}
E possiamo chiamare questa funzione con entrambe le varianti:
enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {}
Usare gli enum ha ancora più vantaggi. Pensando al nostro tipo di indirizzo IP, al momento non abbiamo modo di memorizzare i dati dell'effettivo indirizzo IP; sappiamo solo che tipo è. Poiché hai appena appreso delle struct nel Capitolo 5, potresti essere tentato di affrontare questo problema con le struct come mostrato nel Listing 6-1.
fn main() { enum IpAddrKind { V4, V6, } struct IpAddr { kind: IpAddrKind, address: String, } let home = IpAddr { kind: IpAddrKind::V4, address: String::from("127.0.0.1"), }; let loopback = IpAddr { kind: IpAddrKind::V6, address: String::from("::1"), }; }
Qui, abbiamo definito una struct IpAddr
che ha due campi: un campo kind
che è di tipo IpAddrKind
(l'enum che abbiamo definito in precedenza) e un campo address
di tipo String
. Abbiamo due istanze di questa struct. La prima è home
, e ha il valore IpAddrKind::V4
come suo kind
con dati di indirizzo associati 127.0.0.1
. La seconda istanza è loopback
. Ha l'altra variante di IpAddrKind
come valore del suo kind
, V6
, e ha l'indirizzo ::1
associato. Abbiamo usato una struct per raggruppare insieme i valori kind
e address
, quindi ora la variante è associata al valore.
Tuttavia, rappresentare lo stesso concetto usando solo un enum è più conciso: piuttosto che un enum all'interno di una struct, possiamo mettere i dati direttamente in ciascuna variante dell'enum. Questa nuova definizione dell'enum IpAddr
dice che entrambi i varianti V4
e V6
avranno valori String
associati:
fn main() { enum IpAddr { V4(String), V6(String), } let home = IpAddr::V4(String::from("127.0.0.1")); let loopback = IpAddr::V6(String::from("::1")); }
Colleghiamo i dati direttamente a ciascuna variante dell'enum, quindi non c'è bisogno di una struct aggiuntiva. Qui, è anche più facile vedere un altro dettaglio di come funzionano gli enum: il nome di ciascuna variante di enum che definiamo diventa anche una funzione che costruisce un'istanza dell'enum. Cioè, IpAddr::V4()
è una chiamata di funzione che prende un argomento String
e restituisce un'istanza del tipo IpAddr
. Otteniamo automaticamente questa funzione costruttore come risultato della definizione dell'enum.
C'è un altro vantaggio nell'usare un enum piuttosto che una struct: ogni variante può avere tipi e quantità di dati associati diversi. Gli indirizzi IP di versione quattro avranno sempre quattro componenti numeriche che avranno valori compresi tra 0 e 255. Se volessimo memorizzare gli indirizzi V4
come quattro valori u8
ma esprimere comunque gli indirizzi V6
come un unico valore String
, non potremmo farlo con una struct. Gli enum gestiscono facilmente questo caso:
fn main() { enum IpAddr { V4(u8, u8, u8, u8), V6(String), } let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); }
Abbiamo mostrato diversi modi per definire strutture dati per memorizzare indirizzi IP di versione quattro e di versione sei. Tuttavia, come si scopre, voler memorizzare indirizzi IP e codificare di che tipo sono è così comune che la libreria standard ha una definizione che possiamo usare! Vediamo come la libreria standard definisce IpAddr
: ha l'esatto enum e le varianti che abbiamo definito e usato, ma inserisce i dati dell'indirizzo all'interno delle varianti sotto forma di due struct diverse, che sono definite diversamente per ciascuna variante:
#![allow(unused)] fn main() { struct Ipv4Addr { // --snip-- } struct Ipv6Addr { // --snip-- } enum IpAddr { V4(Ipv4Addr), V6(Ipv6Addr), } }
Questo codice illustra che puoi mettere qualsiasi tipo di dati all'interno di una variante di enum: stringhe, tipi numerici o struct, per esempio. Puoi anche includere un altro enum! Inoltre, i tipi della libreria standard spesso non sono molto più complicati di quanto potresti inventare.
Nota che anche se la libreria standard contiene una definizione per IpAddr
, possiamo ancora creare e usare la nostra definizione senza conflitti poiché non abbiamo portato la definizione della libreria standard nel nostro ambito. Parleremo di più su come portare i tipi in ambito nel Capitolo 7.
Vediamo un altro esempio di un enum nel Listing 6-2: questo ha una vasta gamma di tipi incorporati nelle sue varianti.
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() {}
Questo enum ha quattro varianti con tipi diversi:
Quit
non ha dati associati.Move
ha campi denominati, come fa una struct.Write
include un singoloString
.ChangeColor
include tre valorii32
.
Definire un enum con varianti come quelle nel Listing 6-2 è simile a definire diversi tipi di definizioni di struct, tranne che l'enum non usa la parola chiave struct
e tutte le varianti sono raggruppate insieme sotto il tipo Message
. Le seguenti struct potrebbero contenere gli stessi dati che contengono le varianti di enum precedenti:
struct QuitMessage; // unit struct struct MoveMessage { x: i32, y: i32, } struct WriteMessage(String); // tuple struct struct ChangeColorMessage(i32, i32, i32); // tuple struct fn main() {}
Ma se usassimo le diverse struct, ciascuna delle quali ha il proprio tipo, non potremmo definire facilmente una funzione per accettare uno qualsiasi di questi tipi di messaggi come potremmo fare con l'enum Message
definito nel Listing 6-2, che è un tipo unico.
C'è un'altra somiglianza tra enum e struct: proprio come possiamo definire metodi sulle struct usando impl
, possiamo anche definire metodi sugli enum. Ecco un metodo chiamato call
che potremmo definire sul nostro enum Message
:
fn main() { enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } impl Message { fn call(&self) { // method body would be defined here } } let m = Message::Write(String::from("hello")); m.call(); }
Il corpo del metodo userebbe self
per ottenere il valore su cui abbiamo chiamato il metodo. In questo esempio, abbiamo creato una variabile m
che ha il valore Message::Write(String::from("hello"))
, e questo è ciò che self
sarà nel corpo del metodo call
quando m.call()
viene eseguito.
Vediamo un altro enum nella libreria standard che è molto comune e utile: Option
.
L'Enum Option
e i Suoi Vantaggi Rispetto ai Valori Nulli
Questa sezione esplora uno studio di caso di Option
, un altro enum definito dalla libreria standard. Il tipo Option
codifica lo scenario molto comune in cui un valore potrebbe essere qualcosa o potrebbe essere nulla.
Ad esempio, se richiedi il primo elemento in una lista non vuota, otterrai un valore. Se richiedi il primo elemento in una lista vuota, non otterrai nulla. Esprimere questo concetto in termini di sistema di tipi significa che il compilatore può verificare se hai gestito tutti i casi che dovresti gestire; questa funzionalità può prevenire bug che sono estremamente comuni in altri linguaggi di programmazione.
Il design del linguaggio di programmazione viene spesso considerato in termini delle funzionalità che includi, ma le funzionalità che escludi sono ugualmente importanti. Rust non ha la funzionalità null che molti altri linguaggi hanno. Null è un valore che significa che non esiste un valore lì. Nei linguaggi con null, le variabili possono sempre essere in uno dei due stati: null o non-null.
Nella sua presentazione del 2009 "Null References: The Billion Dollar Mistake", Tony Hoare, l'inventore di null, ha detto questo:
La chiamo il mio errore da miliardi di dollari. A quel tempo, stavo progettando il primo sistema di tipi completo per i riferimenti in un linguaggio orientato agli oggetti. Il mio obiettivo era assicurarmi che tutto l'uso dei riferimenti fosse assolutamente sicuro, con controlli eseguiti automaticamente dal compilatore. Ma non potevo resistere alla tentazione di inserire un riferimento null, semplicemente perché era così facile da implementare. Questo ha portato a innumerevoli errori, vulnerabilità e crash di sistema, che probabilmente hanno causato miliardi di dollari di dolore e danni negli ultimi quarant'anni.
Il problema con i valori nulli è che se provi a usare un valore nullo come se fosse un valore non nullo, otterrai un errore di qualche tipo. Poiché questa proprietà di null o non-null è pervasiva, è estremamente facile commettere questo tipo di errore.
Tuttavia, il concetto che null cerca di esprimere è ancora utile: un null è un valore che è attualmente non valido o assente per qualche motivo.
Il problema non è davvero con il concetto, ma con l'implementazione particolare. Di conseguenza, Rust non ha null, ma ha un enum che può codificare il concetto di un valore presente o assente. Questo enum è Option<T>
, ed è definito dalla libreria standard come segue:
#![allow(unused)] fn main() { enum Option<T> { None, Some(T), } }
L'enum Option<T>
è così utile che è persino incluso nel prelude; non è necessario portarlo in ambito esplicitamente. Le sue varianti sono anche incluse nel prelude: puoi usare Some
e None
direttamente senza il prefisso Option::
. L'enum Option<T>
è comunque solo un enum regolare, e Some(T)
e None
sono ancora varianti del tipo Option<T>
.
La sintassi <T>
è una funzione di Rust di cui non abbiamo ancora parlato. È un parametro di tipo generico, e ne parleremo più in dettaglio nel Capitolo 10. Per ora, tutto ciò che devi sapere è che <T>
significa che la variante Some
dell'enum Option
può contenere un dato pezzo di dato di qualsiasi tipo, e che ogni tipo concreto che viene usato al posto di T
rende il tipo complessivo Option<T>
un tipo diverso. Ecco alcuni esempi di utilizzo dei valori Option
per contenere tipi numerici e tipi di stringa:
fn main() { let some_number = Some(5); let some_char = Some('e'); let absent_number: Option<i32> = None; }
Il tipo di some_number
è Option<i32>
. Il tipo di some_char
è Option<char>
, che è un tipo diverso. Rust può inferire questi tipi perché abbiamo specificato un valore all'interno della variante Some
. Per absent_number
, Rust richiede di annotare il tipo complessivo Option
: il compilatore non può inferire il tipo che la variante Some
corrispondente conterrà guardando solo un valore None
. Qui, diciamo a Rust che intendiamo che absent_number
sia di tipo Option<i32>
.
Quando abbiamo un valore Some
, sappiamo che un valore è presente e che il valore è contenuto all'interno del Some
. Quando abbiamo un valore None
, in un certo senso significa la stessa cosa di null: non abbiamo un valore valido. Quindi perché avere Option<T>
è migliore di avere null?
In breve, poiché Option<T>
e T
(dove T
può essere qualsiasi tipo) sono tipi diversi, il compilatore non ci permetterà di usare un valore Option<T>
come se fosse sicuramente un valore valido. Ad esempio, questo codice non compila, perché sta cercando di aggiungere un i8
a un Option<i8>
:
fn main() {
let x: i8 = 5;
let y: Option<i8> = Some(5);
let sum = x + y;
}
Se eseguiamo questo codice, otteniamo un messaggio di errore come questo:
$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0277]: cannot add `Option<i8>` to `i8`
--> src/main.rs:5:17
|
5 | let sum = x + y;
| ^ no implementation for `i8 + Option<i8>`
|
= help: the trait `Add<Option<i8>>` is not implemented for `i8`
= help: the following other types implement trait `Add<Rhs>`:
<&'a i8 as Add<i8>>
<&i8 as Add<&i8>>
<i8 as Add<&i8>>
<i8 as Add>
For more information about this error, try `rustc --explain E0277`.
error: could not compile `enums` due to previous error
Intenso! In effetti, questo messaggio di errore significa che Rust non sa come aggiungere un i8
e un Option<i8>
, perché sono tipi diversi. Quando abbiamo un valore di un tipo come i8
in Rust, il compilatore si assicurerà che abbiamo sempre un valore valido. Possiamo proseguire con fiducia senza dover controllare il null prima di usare quel valore. Solo quando abbiamo un Option<i8>
(o qualsiasi altro tipo di valore con cui stiamo lavorando) dobbiamo preoccuparci di non avere un valore, e il compilatore si assicurerà che gestiamo quel caso prima di usare il valore.
In altre parole, devi convertire un Option<T>
in un T
prima di poter eseguire operazioni sul T
. In generale, questo aiuta a catturare uno dei problemi più comuni con il null: supporre che qualcosa non sia null quando invece lo è.
Eliminare il rischio di supporre erroneamente un valore non nullo ti aiuta a essere più sicuro del tuo codice. Per avere un valore che potrebbe essere null, devi esplicitamente optare per quella possibilità rendendo il tipo di quel valore Option<T>
. Poi, quando usi quel valore, sei tenuto a gestire esplicitamente il caso in cui il valore è null. Ovunque un valore abbia un tipo che non è un Option<T>
, puoi tranquillamente supporre che il valore non sia null. Questa è stata una decisione di design deliberata per Rust al fine di limitare la pervasività del null e aumentare la sicurezza del codice Rust.
Quindi, come ottieni il valore T
da una variante Some
quando hai un valore di tipo Option<T>
in modo da poter usare quel valore? L'enum Option<T>
ha un gran numero di metodi utili in una varietà di situazioni; puoi controllarli nella sua documentazione. Familiarizzare con i metodi su Option<T>
sarà estremamente utile nel tuo percorso con Rust.
In generale, per utilizzare un valore Option<T>
, si desidera avere del codice che gestisca ogni variante. Si desidera del codice che verrà eseguito solo quando si ha un valore Some(T)
, e questo codice è autorizzato a utilizzare l'interno T
. Si desidera un altro codice che verrà eseguito solo se si ha un valore None
, e tale codice non ha un valore T
disponibile. L'espressione match
è una struttura di controllo del flusso che fa proprio questo quando utilizzata con gli enum: eseguirà codice diverso a seconda della variante dell'enum che ha, e quel codice può utilizzare i dati all'interno del valore corrispondente.
Il Costrutto di Flusso di Controllo match
Rust ha un costrutto di flusso di controllo estremamente potente chiamato match
che
ti permette di confrontare un valore con una serie di pattern e poi eseguire
il codice basato su quale pattern corrisponde. I pattern possono essere costituiti da valori letterali,
nomi di variabili, jolly e molte altre cose; Capitolo
18 copre tutti i diversi tipi di pattern
e cosa fanno. La potenza di match
deriva dall'espressività dei
pattern e dal fatto che il compilatore conferma che tutti i casi possibili sono
gestiti.
Pensa a un'espressione match
come a una macchina selezionatrice di monete: le monete scivolano
giù su una pista con buchi di varie dimensioni, e ogni moneta cade attraverso
il primo buco che incontra e che è adatto alla sua dimensione. Allo stesso modo, i valori percorrono
ogni pattern in un match
, e al primo pattern che il valore “adatta”,
il valore cade nel blocco di codice associato per essere utilizzato durante l'esecuzione.
Parlando di monete, usiamole come esempio usando match
! Possiamo scrivere una
funzione che prende una moneta statunitense sconosciuta e, in modo simile a una macchina per contare,
determina quale moneta è e ne restituisce il valore in centesimi, come mostrato
nell'Elenco 6-3.
enum Coin { Penny, Nickel, Dime, Quarter, } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, } } fn main() {}
Analizziamo il match
nella funzione value_in_cents
. Prima elenchiamo
la parola chiave match
seguita da un'espressione, che in questo caso è il valore
coin
. Questo sembra molto simile a un'espressione condizionale usata con if
, ma
c'è una grande differenza: con if
, la condizione deve essere valutata come
valore booleano, ma qui può essere di qualsiasi tipo. Il tipo di coin
in questo esempio
è l'enum Coin
che abbiamo definito nella prima riga.
Successivamente ci sono i bracci del match
. Un braccio ha due parti: un pattern e un po' di codice. Il
primo braccio qui ha un pattern che è il valore Coin::Penny
e poi l'operatore =>
che separa il pattern e il codice da eseguire. Il codice in questo caso
è solo il valore 1
. Ogni braccio è separato dal successivo con una virgola.
Quando l'espressione match
viene eseguita, confronta il valore risultante con
il pattern di ogni braccio, in ordine. Se un pattern corrisponde al valore,
il codice associato a quel pattern viene eseguito. Se quel pattern non corrisponde
al valore, l'esecuzione continua verso il braccio successivo, come in una macchina selezionatrice di monete.
Possiamo avere quanti bracci vogliamo: nell'Elenco 6-3, il nostro match
ha quattro bracci.
Il codice associato a ogni braccio è un'espressione, e il valore risultante
dell'espressione nel braccio corrispondente è il valore che viene restituito per l'intera
espressione match
.
Di solito non usiamo le parentesi graffe se il codice del braccio del match è breve, come nel
caso dell'Elenco 6-3 dove ogni braccio restituisce solo un valore. Se vuoi eseguire più
righe di codice in un braccio del match, devi usare le parentesi graffe, e la virgola
successiva al braccio diventa facoltativa. Ad esempio, il seguente codice stampa
“Penny fortunato!” ogni volta che il metodo viene chiamato con un Coin::Penny
, ma ritorna comunque
l'ultimo valore del blocco, 1
:
enum Coin { Penny, Nickel, Dime, Quarter, } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => { println!("Lucky penny!"); 1 } Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, } } fn main() {}
Pattern che Si Legano ai Valori
Un'altra caratteristica utile dei bracci del match è che possono legarsi alle parti dei valori che corrispondono al pattern. Questo è il modo in cui possiamo estrarre valori dalle varianti dell'enum.
Come esempio, cambiamo una delle nostre varianti dell'enum per includere dati all’interno.
Dal 1999 al 2008, gli Stati Uniti hanno coniato quarti di dollaro con diversi
design per ciascuno dei 50 stati su un lato. Nessun'altra moneta ha avuto design statali,
quindi solo i quarti di dollaro hanno questo valore extra. Possiamo aggiungere questa informazione al
nostro enum
cambiando la variante Quarter
per includere un valore UsState
memorizzato all'interno, come abbiamo fatto nell'Elenco 6-4.
#[derive(Debug)] // so we can inspect the state in a minute enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() {}
Immaginiamo che un amico stia cercando di raccogliere tutti i 50 quarti di stato. Mentre ordiniamo il nostro resto per tipo di moneta, annunceremo anche il nome dello stato associato a ciascun quarto in modo che, se non l'ha ancora, possa aggiungerlo alla sua collezione.
Nell'espressione match per questo codice, aggiungiamo una variabile chiamata state
al pattern
che corrisponde ai valori della variante Coin::Quarter
. Quando un
Coin::Quarter
corrisponde, la variabile state
si legherà al valore dello
stato di quel quarto di dollaro. Poi possiamo utilizzare state
nel codice per quel braccio, come segue:
#[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter(state) => { println!("State quarter from {:?}!", state); 25 } } } fn main() { value_in_cents(Coin::Quarter(UsState::Alaska)); }
Se dovessimo chiamare value_in_cents(Coin::Quarter(UsState::Alaska))
, coin
sarebbe Coin::Quarter(UsState::Alaska)
. Quando confrontiamo quel valore con ciascuno
dei bracci del match, nessuno di loro corrisponde finché non raggiungiamo Coin::Quarter(state)
.
A quel punto, l'associazione per state
sarà il valore UsState::Alaska
. Possiamo
poi utilizzare tale associazione nell'espressione println!
, ottenendo quindi il valore
interno dello stato dalla variante dell'enum Coin
per Quarter
.
Matching con Option<T>
Nella sezione precedente, volevamo ottenere il valore interno T
dal caso Some
quando usavamo Option<T>
; possiamo anche gestire Option<T>
usando match
, come
abbiamo fatto con l'enum Coin
! Invece di confrontare le monete, confronteremo
le varianti di Option<T>
, ma il modo in cui funziona l'espressione match
rimane lo stesso.
Supponiamo di voler scrivere una funzione che prende un Option<i32>
e, se
c'è un valore all'interno, aggiunge 1 a quel valore. Se non c'è un valore all'interno,
la funzione dovrebbe restituire il valore None
e non tentare di eseguire nessuna
operazione.
Questa funzione è molto facile da scrivere, grazie a match
, e apparirà come
nell'Elenco 6-5.
fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); }
Esaminiamo la prima esecuzione di plus_one
in dettaglio. Quando chiamiamo
plus_one(five)
, la variabile x
nel corpo di plus_one
avrà il
valore Some(5)
. Poi confrontiamo questo valore con ciascun braccio del match:
fn main() {
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
Il valore Some(5)
non corrisponde al pattern None
, quindi continuiamo al
braccio successivo:
fn main() {
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
Il valore Some(5)
corrisponde a Some(i)
? Sì, corrisponde! Abbiamo la stessa variante.
La variabile i
si lega al valore contenuto in Some
, quindi i
prende il valore
5
. Il codice nel braccio del match viene poi eseguito, quindi aggiungiamo 1 al valore di
i
e creiamo un nuovo valore Some
con il nostro totale 6
all'interno.
Ora consideriamo la seconda chiamata di plus_one
nell'Elenco 6-5, dove x
è
None
. Entriamo nel match
e confrontiamo con il primo braccio:
fn main() {
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
Corrisponde! Non c'è valore a cui aggiungere, quindi il programma si ferma e restituisce il
valore None
sul lato destro di =>
. Poiché il primo braccio ha corrisposto, nessun altro
braccio viene confrontato.
Combinare match
e enum è utile in molte situazioni. Vedrai spesso
questo pattern nel codice Rust: match
contro un enum, associare una variabile ai dati
interni e poi eseguire del codice basato su di esso. È un po' complicato all'inizio, ma
una volta che ti ci abitui, desidererai averlo in tutti i linguaggi. È
costantemente un favorito degli utenti.
I Match sono Esaustivi
C'è un altro aspetto di match
di cui dobbiamo discutere: i pattern dei bracci devono
coprire tutte le possibilità. Considera questa versione della nostra funzione plus_one
,
che ha un bug e non compilerà:
fn main() {
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
Non abbiamo gestito il caso None
, quindi questo codice causerà un bug. Fortunatamente, è
un bug che Rust sa come catturare. Se proviamo a compilare questo codice, otterremo questo
errore:
$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0004]: non-exhaustive patterns: `None` not covered
--> src/main.rs:3:15
|
3 | match x {
| ^ pattern `None` not covered
|
note: `Option<i32>` defined here
--> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:518:1
|
= note:
/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:522:5: not covered
= note: the matched value is of type `Option<i32>`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
4 ~ Some(i) => Some(i + 1),
5 ~ None => todo!(),
|
For more information about this error, try `rustc --explain E0004`.
error: could not compile `enums` due to previous error
Rust sa che non abbiamo coperto tutti i casi possibili, e sa persino quale
pattern abbiamo dimenticato! I match in Rust sono esaustivi: dobbiamo esaurire ogni ultima
possibilità affinché il codice sia valido. Soprattutto nel caso
di Option<T>
, quando Rust ci impedisce di dimenticare di gestire esplicitamente il caso
None
, ci protegge dall'assumere di avere un valore quando potremmo avere null,
rendendo così impossibile l'errore miliardario di cui abbiamo parlato prima.
Pattern Generici e il Segnaposto _
Usando gli enum, possiamo anche intraprendere azioni speciali per alcuni valori
particolari, ma per tutti gli altri valori intraprendere un'azione predefinita. Immagina di
stare implementando un gioco in cui, se tiri 3 con un dado, il tuo giocatore non si muove,
ma riceve invece un nuovo cappello elegante. Se tiri un 7, il tuo giocatore perde un
cappello elegante. Per tutti gli altri valori, il tuo giocatore si muove di quel numero di
spazi sul tabellone. Ecco un match
che implementa quella logica, con il risultato del
tiro di dado codificato anziché un valore casuale, e tutta l'altra logica rappresentata da
funzioni senza corpi perché implementarle realmente è fuori dal nostro scopo:
fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), other => move_player(other), } fn add_fancy_hat() {} fn remove_fancy_hat() {} fn move_player(num_spaces: u8) {} }
Per i primi due bracci, i pattern sono i valori letterali 3
e 7
. Per
l'ultimo braccio che copre ogni altro valore possibile, il pattern è la
variabile che abbiamo scelto di chiamare other
. Il codice che viene eseguito per il braccio
other
utilizza la variabile passandola alla funzione move_player
.
Questo codice compila, anche se non abbiamo elencato tutti i possibili valori che un
u8
può avere, perché l'ultimo pattern catturerà tutti i valori non specificamente
elencati. Questo pattern generico soddisfa il requisito che il match
debba essere
esaustivo. Nota che dobbiamo mettere l'ultimo braccio generico perché i
pattern vengono valutati in ordine. Se mettessimo il braccio generico prima, gli altri
bracci non verrebbero mai eseguiti, quindi Rust ci avviserà se aggiungiamo bracci dopo un catch-all!
Rust ha anche un pattern che possiamo utilizzare quando vogliamo un catch-all ma non vogliamo
utilizzare il valore nel pattern catch-all: _
è un pattern speciale che corrisponde
a qualsiasi valore e non si lega a tale valore. Questo dice a Rust che non useremo
il valore, quindi Rust non ci avviserà riguardo a una variabile non utilizzata.
Cambiamo le regole del gioco: ora, se tiri qualcosa diverso da un 3 o un 7,
devi tirare di nuovo il dado. Non abbiamo più bisogno di utilizzare il valore generico,
quindi possiamo cambiare il nostro codice per usare _
invece della variabile chiamata other
:
fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), _ => reroll(), } fn add_fancy_hat() {} fn remove_fancy_hat() {} fn reroll() {} }
Questo esempio soddisfa anche il requisito di esaustività perché stiamo esplicitamente ignorando tutti gli altri valori nell'ultimo braccio; non abbiamo dimenticato nulla.
Infine, cambieremo ancora una volta le regole del gioco così che non succeda
nulla nel tuo turno se tiri qualcosa diverso da un 3 o 7. Possiamo esprimere
questo usando il valore unitario (il tipo di tuple vuoto di cui abbiamo parlato nella “Il tipo
Tuple”) come il codice che segue il braccio _
:
fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), _ => (), } fn add_fancy_hat() {} fn remove_fancy_hat() {} }
Qui, stiamo dicendo a Rust esplicitamente che non useremo nessun altro valore che non corrisponde a un pattern in un braccio precedente, e non vogliamo eseguire alcun codice in questo caso.
Parleremo più in dettaglio di pattern e match nel Capitolo
18. Per ora, passeremo alla sintassi if let
, che può essere utile in
situazioni in cui l'espressione match
è un po' prolissa.
Flusso di Controllo Conciso con if let
La sintassi if let
ti permette di combinare if
e let
in un modo meno verboso per gestire valori che corrispondono a un pattern, ignorando il resto. Considera il programma in Listing 6-6 che fa il match su un valore Option<u8>
nella variabile config_max
, ma vuole eseguire il codice solo se il valore è la variante Some
.
fn main() { let config_max = Some(3u8); match config_max { Some(max) => println!("The maximum is configured to be {}", max), _ => (), } }
Se il valore è Some
, stampiamo il valore nella variante Some
legando il valore alla variabile max
nel pattern. Non vogliamo fare nulla con il valore None
. Per soddisfare l'espressione match
, dobbiamo aggiungere _ => ()
dopo aver elaborato solo una variante, il che è un codice boilerplate fastidioso da aggiungere.
Invece, potremmo scrivere questo in un modo più breve usando if let
. Il seguente codice si comporta allo stesso modo del match
in Listing 6-6:
fn main() { let config_max = Some(3u8); if let Some(max) = config_max { println!("The maximum is configured to be {}", max); } }
La sintassi if let
prende un pattern e un'espressione separati da un segno uguale. Funziona allo stesso modo di un match
, dove l'espressione è data al match
e il pattern è il suo primo braccio. In questo caso, il pattern è Some(max)
, e max
viene legato al valore all'interno di Some
. Possiamo quindi usare max
nel corpo del blocco if let
nello stesso modo in cui usavamo max
nel corrispondente braccio di match
. Il codice nel blocco if let
non viene eseguito se il valore non corrisponde al pattern.
Usare if let
significa meno digitazione, meno indentazione e meno codice boilerplate. Tuttavia, perdi il controllo esaustivo che match
impone. Scegliere tra match
e if let
dipende da cosa stai facendo nella tua particolare situazione e se guadagnare concisione è uno scambio appropriato per perdere il controllo esaustivo.
In altre parole, puoi pensare a if let
come zucchero sintattico per un match
che esegue codice quando il valore corrisponde a un pattern e poi ignora tutti gli altri valori.
Possiamo includere un else
con un if let
. Il blocco di codice che va con l'else
è lo stesso del blocco di codice che andrebbe con il caso _
nell'espressione match
equivalente a if let
e else
. Ricorda la definizione dell'enum Coin
in Listing 6-4, dove la variante Quarter
conteneva anche un valore UsState
. Se volessimo contare tutte le monete non-quarter che vediamo mentre annunciamo anche lo stato dei quarter, potremmo farlo con un'espressione match
, così:
#[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() { let coin = Coin::Penny; let mut count = 0; match coin { Coin::Quarter(state) => println!("State quarter from {:?}!", state), _ => count += 1, } }
Oppure potremmo usare un'espressione if let
e else
, così:
#[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() { let coin = Coin::Penny; let mut count = 0; if let Coin::Quarter(state) = coin { println!("State quarter from {:?}!", state); } else { count += 1; } }
Se hai una situazione in cui la logica del tuo programma è troppo verbosa da esprimere usando un match
, ricorda che if let
è anche nella tua cassetta degli attrezzi di Rust.
Sommario
Abbiamo ora coperto come usare gli enum per creare tipi personalizzati che possono essere uno di un set di valori enumerati. Abbiamo mostrato come il tipo Option<T>
della libreria standard ti aiuta a usare il sistema dei tipi per prevenire errori. Quando i valori degli enum hanno dati al loro interno, puoi usare match
o if let
per estrarre e usare quei valori, a seconda di quanti casi devi gestire.
I tuoi programmi Rust ora possono esprimere concetti nel tuo dominio usando struct e enum. Creare tipi personalizzati da usare nella tua API assicura la sicurezza dei tipi: il compilatore garantirà che le tue funzioni ottengano solo valori del tipo che ogni funzione si aspetta.
Per fornire una API ben organizzata ai tuoi utenti che sia semplice da usare e che esponga esattamente ciò di cui hanno bisogno, passiamo ora ai moduli di Rust.
Gestire Progetti Crescenti con Packages, Crates e Moduli
Man mano che scrivi programmi più grandi, organizzare il codice diventerà sempre più importante. Raggruppando la funzionalità correlata e separando il codice con caratteristiche distinte, chiarirai dove trovare il codice che implementa una particolare funzionalità e dove andare per cambiare il funzionamento di una funzionalità.
I programmi che abbiamo scritto finora sono stati in un modulo in un file. Man mano che un progetto cresce, dovresti organizzare il codice suddividendolo in più moduli e poi in più file. Un package può contenere più binary crates e opzionalmente un library crate. Man mano che un package cresce, puoi estrarre parti in crate separati che diventano dipendenze esterne. Questo capitolo copre tutte queste tecniche. Per i progetti molto grandi comprendenti un insieme di packages interrelati che evolvono insieme, Cargo fornisce workspaces, che tratteremo nella sezione “Cargo Workspaces” del Capitolo 14.
Parleremo anche di come incapsulare i dettagli dell'implementazione, il che ti consente di riutilizzare il codice a un livello superiore: una volta che hai implementato un'operazione, altro codice può chiamare il tuo codice tramite la sua interfaccia pubblica senza dover sapere come funziona l'implementazione. Il modo in cui scrivi il codice definisce quali parti sono pubbliche per l'uso da parte di altro codice e quali parti sono dettagli privati di implementazione che ti riservi il diritto di cambiare. Questo è un altro modo per limitare la quantità di dettagli che devi mantenere nella tua mente.
Un concetto correlato è lo scope: il contesto annidato in cui è scritto il codice ha un insieme di nomi definiti come "in scope". Quando leggon, scrivono e compilano il codice, programmatori e compilatori devono sapere se un particolare nome in un determinato punto si riferisce a una variabile, funzione, struct, enum, modulo, costante o altro elemento e cosa significa quell'elemento. Puoi creare scopes e cambiare quali nomi sono in o fuori dallo scope. Non puoi avere due elementi con lo stesso nome nello stesso scope; sono disponibili strumenti per risolvere conflitti di nomi.
Rust ha una serie di funzionalità che ti permettono di gestire l'organizzazione del tuo codice, inclusa l'esposizione di determinati dettagli, quali dettagli sono privati e quali nomi sono in ciascuno scope nei tuoi programmi. Queste funzionalità, talvolta collettivamente denominate module system, includono:
- Packages: Una funzionalità di Cargo che ti consente di costruire, testare e condividere crates
- Crates: Un albero di moduli che produce una libreria o un eseguibile
- Modules e use: Ti consentono di controllare l'organizzazione, lo scope e la privacy dei paths
- Paths: Un modo di nominare un elemento, come una struct, funzione, o modulo
In questo capitolo, copriremo tutte queste funzionalità, discuteremo di come interagiscono e spiegheremo come usarle per gestire lo scope. Alla fine, dovresti avere una solida comprensione del module system e essere in grado di lavorare con gli scopes come un professionista!
Package e Crate
Le prime parti del sistema dei moduli che affronteremo sono i package e i crate.
Un crate è la quantità minima di codice che il compilatore Rust considera alla volta. Anche se esegui rustc
invece di cargo
e passi un singolo file di codice sorgente (come abbiamo fatto nella sezione "Scrivere ed eseguire un programma Rust" del Capitolo 1), il compilatore considera quel file come un crate. I crate possono contenere moduli, e i moduli possono essere definiti in altri file che vengono compilati con il crate, come vedremo nelle sezioni successive.
Un crate può presentarsi in due forme: un crate binario o un crate di librerie.
I crate binari sono programmi che puoi compilare in un eseguibile che puoi eseguire, come un programma da riga di comando o un server. Ognuno deve avere una funzione chiamata main
che definisce cosa succede quando l'eseguibile viene eseguito. Tutti i crate che abbiamo creato finora erano crate binari.
I crate di librerie non hanno una funzione main
e non vengono compilati in un eseguibile. Invece, definiscono funzionalità destinate a essere condivise con più progetti. Ad esempio, il crate rand
che abbiamo usato nel Capitolo 2 fornisce funzionalità che generano numeri casuali. La maggior parte delle volte, quando i Rustaceans dicono "crate", intendono un crate di libreria, e usano "crate" in modo intercambiabile con il concetto generale di programmazione di una "libreria".
La radice del crate è un file sorgente da cui il compilatore Rust parte e costituisce il modulo radice del tuo crate (spiegheremo i moduli in dettaglio nella sezione “Definire Moduli per Controllare Scope e Privacy”).
Un package è un insieme di uno o più crate che fornisce un set di funzionalità. Un package contiene un file Cargo.toml che descrive come costruire quei crate. Cargo è in realtà un package che contiene il crate binario per lo strumento da riga di comando che hai utilizzato per costruire il tuo codice. Il package Cargo contiene anche un crate di libreria da cui dipende il crate binario. Altri progetti possono dipendere dal crate di libreria di Cargo per usare la stessa logica che usa lo strumento da riga di comando Cargo.
Un crate può presentarsi in due forme: un crate binario o un crate di libreria. Un package può contenere quanti crate binari vuoi, ma al massimo solo un crate di libreria. Un package deve contenere almeno un crate, sia che si tratti di una libreria o di un crate binario.
Vediamo cosa succede quando creiamo un package. Prima inseriamo il comando cargo new my-project
:
$ cargo new my-project
Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs
Dopo aver eseguito cargo new my-project
, usiamo ls
per vedere cosa crea Cargo. Nella directory del progetto, c'è un file Cargo.toml, che ci fornisce un package. C'è anche una directory src che contiene main.rs. Apri Cargo.toml nel tuo editor di testo e nota che non c'è menzione di src/main.rs. Cargo segue una convenzione secondo cui src/main.rs è la radice del crate di un crate binario con lo stesso nome del package. Allo stesso modo, Cargo sa che se la directory del package contiene src/lib.rs, il package contiene un crate di libreria con lo stesso nome del package, e src/lib.rs è la sua radice del crate. Cargo passa i file di radice del crate a rustc
per costruire la libreria o il binario.
Qui, abbiamo un package che contiene solo src/main.rs, il che significa che contiene solo un crate binario chiamato my-project
. Se un package contiene src/main.rs e src/lib.rs, ha due crate: uno binario e uno di libreria, entrambi con lo stesso nome del package. Un package può avere più crate binari posizionando file nella directory src/bin: ogni file sarà un crate binario separato.
Definire Moduli per Controllare l'Ambito e la Privacy
In questa sezione parleremo dei moduli e di altre parti del sistema dei moduli,
ovvero dei percorsi, che ti permettono di dare un nome agli elementi; della parola chiave use
che porta un percorso nell'ambito; e della parola chiave pub
per rendere pubblici gli elementi. Discuteremo anche della parola chiave as
, dei pacchetti esterni e dell'operatore glob.
Riepilogo sui Moduli
Prima di entrare nei dettagli dei moduli e dei percorsi, forniamo un rapido
riferimento su come funzionano i moduli, i percorsi, la parola chiave use
e la parola chiave pub
nel compilatore e su come la maggior parte degli sviluppatori organizza il proprio codice. Vedremo esempi di ciascuna di queste regole in tutto questo capitolo, ma questo è un ottimo posto a cui fare riferimento come promemoria su come funzionano i moduli.
- Inizia dalla radice del crate: Quando compili un crate, il compilatore cerca prima nel file radice del crate (di solito src/lib.rs per un crate di libreria o src/main.rs per un crate binario) il codice da compilare.
- Dichiarare moduli: Nel file radice del crate, puoi dichiarare nuovi moduli;
ad esempio puoi dichiarare un modulo “garden” con
mod garden;
. Il compilatore cercherà il codice del modulo in questi luoghi:- Inline, tra parentesi graffe che sostituiscono il punto e virgola dopo
mod garden
- Nel file src/garden.rs
- Nel file src/garden/mod.rs
- Inline, tra parentesi graffe che sostituiscono il punto e virgola dopo
- Dichiarare sottomoduli: In qualsiasi file diverso dalla radice del crate, puoi
dichiarare sottomoduli. Ad esempio, puoi dichiarare
mod vegetables;
in src/garden.rs. Il compilatore cercherà il codice del sottomodulo all'interno della directory denominata come il modulo padre in questi luoghi:- Inline, direttamente dopo
mod vegetables
, tra parentesi graffe anziché il punto e virgola - Nel file src/garden/vegetables.rs
- Nel file src/garden/vegetables/mod.rs
- Inline, direttamente dopo
- Percorsi verso il codice nei moduli: Una volta che un modulo fa parte del tuo crate,
puoi fare riferimento al codice in quel modulo da qualsiasi altra parte nello stesso crate,
purché le regole di privacy lo permettano, utilizzando il percorso verso il codice. Ad esempio, un
tipo
Asparagus
nel modulo vegetables del giardino si troverà incrate::garden::vegetables::Asparagus
. - Privato vs. pubblico: Il codice all'interno di un modulo è privato rispetto ai suoi moduli genitori
per impostazione predefinita. Per rendere un modulo pubblico, dichiaralo con
pub mod
anzichémod
. Per rendere pubblici anche gli elementi all'interno di un modulo pubblico, usapub
davanti alle loro dichiarazioni. - La parola chiave
use
: All'interno di un ambito, la parola chiaveuse
crea scorciatoie per gli elementi per ridurre la ripetizione di percorsi lunghi. In qualsiasi ambito che può fare riferimento acrate::garden::vegetables::Asparagus
, puoi creare una scorciatoia conuse crate::garden::vegetables::Asparagus;
e da quel momento in poi devi solo scrivereAsparagus
per utilizzare quel tipo nell'ambito.
Qui, creiamo un crate binario chiamato backyard
che illustra queste regole.
La directory del crate, anch'essa chiamata backyard
, contiene questi file e
directory:
backyard
├── Cargo.lock
├── Cargo.toml
└── src
├── garden
│ └── vegetables.rs
├── garden.rs
└── main.rs
Il file radice del crate in questo caso è src/main.rs, e contiene:
Nome del file: src/main.rs
use crate::garden::vegetables::Asparagus;
pub mod garden;
fn main() {
let plant = Asparagus {};
println!("I'm growing {:?}!", plant);
}
La linea pub mod garden;
dice al compilatore di includere il codice che trova in
src/garden.rs, che è:
Nome del file: src/garden.rs
pub mod vegetables;
Qui, pub mod vegetables;
significa che anche il codice in src/garden/vegetables.rs è
incluso. Quel codice è:
#[derive(Debug)]
pub struct Asparagus {}
Ora entriamo nei dettagli di queste regole e dimostriamole in azione!
Raggruppare Codice Correlato in Moduli
I moduli ci permettono di organizzare il codice all'interno di un crate per una migliore leggibilità e facile riutilizzo. I moduli ci permettono anche di controllare la privacy degli elementi poiché il codice all'interno di un modulo è privato per impostazione predefinita. Gli elementi privati sono dettagli di implementazione interna non disponibili per l'uso esterno. Possiamo scegliere di rendere pubblici i moduli e gli elementi contenuti, esponendoli per consentire al codice esterno di utilizzarli e dipendere su di essi.
Ad esempio, scriviamo un crate di libreria che fornisce la funzionalità di un ristorante. Definiremo le firme delle funzioni ma lasceremo i loro corpi vuoti per concentrarci sull'organizzazione del codice piuttosto che sull'implementazione di un ristorante.
Nell'industria della ristorazione, alcune parti di un ristorante sono denominate front of house e altre back of house. Il front of house è dove si trovano i clienti; questo include dove i camerieri accolgono i clienti, i camerieri prendono ordini e pagamenti e i baristi preparano i drink. Il back of house è dove gli chef e i cuochi lavorano in cucina, i lavapiatti puliscono e i gestori fanno lavori amministrativi.
Per strutturare il nostro crate in questo modo, possiamo organizzare le sue funzioni in moduli
nidificati. Crea una nuova libreria chiamata restaurant
eseguendo cargo new restaurant --lib
. Poi inserisci il codice in Listing 7-1 in src/lib.rs per
definire alcuni moduli e le firme delle funzioni; questo codice è la sezione front of house.
Nome del file: src/lib.rs
mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn serve_order() {}
fn take_payment() {}
}
}
Definiamo un modulo con la parola chiave mod
seguita dal nome del modulo
(in questo caso, front_of_house
). Il corpo del modulo va poi dentro parentesi
graffe. All'interno dei moduli, possiamo posizionare altri moduli, come in questo caso con i
moduli hosting
e serving
. I moduli possono anche contenere definizioni per altri
elementi, come struct, enum, costanti, trait, e — come in Listing
7-1 — funzioni.
Utilizzando i moduli, possiamo raggruppare definizioni correlate insieme e dire perché sono correlate. I programmatori che usano questo codice possono navigare nel codice in base ai gruppi anziché dover leggere tutte le definizioni, rendendo più facile trovare le definizioni rilevanti per loro. I programmatori che aggiungono nuova funzionalità a questo codice sapranno dove posizionare il codice per mantenere l'organizzazione del programma.
In precedenza, abbiamo menzionato che src/main.rs e src/lib.rs sono chiamati radici
del crate. Il motivo del loro nome è che il contenuto di uno di questi due
file forma un modulo chiamato crate
alla radice della struttura del modulo
del crate, noto come albero del modulo.
L'elenco 7-2 mostra l'albero del modulo per la struttura nell'elenco 7-1.
crate
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment
Questo albero mostra come alcuni moduli si nidificano all'interno di altri moduli; ad esempio,
hosting
si nidifica dentro front_of_house
. L'albero mostra anche che alcuni moduli
sono fratelli, cioè sono definiti nello stesso modulo; hosting
e
serving
sono fratelli definiti dentro front_of_house
. Se il modulo A è
contenuto dentro il modulo B, diciamo che il modulo A è il figlio del modulo B e
che il modulo B è il genitore del modulo A. Nota che l'intero albero dei moduli
è radicato sotto il modulo implicito chiamato crate
.
L'albero del modulo potrebbe ricordarti l'albero delle directory nel filesystem sul tuo computer; questo è un paragone molto appropriato! Proprio come le directory in un filesystem, usiamo i moduli per organizzare il nostro codice. E proprio come i file in una directory, abbiamo bisogno di un modo per trovare i nostri moduli.
Percorsi per Fare Riferimento a un Elemento nell'Albero dei Moduli
Per mostrare a Rust dove trovare un elemento in un albero dei moduli, usiamo un percorso nello stesso modo in cui utilizziamo un percorso quando navighiamo in un filesystem. Per chiamare una funzione, dobbiamo conoscere il suo percorso.
Un percorso può assumere due forme:
- Un percorso assoluto è il percorso completo che inizia dalla radice di un crate; per il codice
da un crate esterno, il percorso assoluto inizia con il nome del crate, e per
il codice dal crate corrente, inizia con la parola letterale
crate
. - Un percorso relativo inizia dal modulo corrente e utilizza
self
,super
o un identificatore nel modulo corrente.
Sia i percorsi assoluti che quelli relativi sono seguiti da uno o più identificatori
separati da doppio due punti (::
).
Tornando a Listing 7-1, supponiamo di voler chiamare la funzione add_to_waitlist
.
Questo è lo stesso che chiedersi: qual è il percorso della funzione add_to_waitlist
?
La lista 7-3 contiene la lista 7-1 con alcuni dei moduli e delle funzioni
rimossi.
Mostreremo due modi per chiamare la funzione add_to_waitlist
da una nuova funzione,
eat_at_restaurant
, definita nella radice del crate. Questi percorsi sono corretti, ma
c'è un altro problema rimanente che impedirà a questo esempio di compilarsi
così com'è. Spiegheremo perché tra un po'.
La funzione eat_at_restaurant
fa parte dell'API pubblica del nostro crate di libreria, quindi
la contrassegniamo con la parola chiave pub
. Nella sezione [“Esposizione dei Percorsi con la parola chiave pub
”][pub], entreremo più nel dettaglio su pub
.
Nome del file: src/lib.rs
mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
La prima volta che chiamiamo la funzione add_to_waitlist
in eat_at_restaurant
,
usiamo un percorso assoluto. La funzione add_to_waitlist
è definita nello stesso
crate di eat_at_restaurant
, il che significa che possiamo usare la parola chiave crate
per
iniziare un percorso assoluto. Includiamo quindi ciascuno dei moduli successivi fino a
raggiungere add_to_waitlist
. Puoi immaginare un filesystem con la stessa
struttura: specificheremo il percorso /front_of_house/hosting/add_to_waitlist
per
eseguire il programma add_to_waitlist
; usare il nome del crate
per iniziare dalla
radice del crate è come usare /
per iniziare dalla radice del filesystem nella tua shell.
La seconda volta che chiamiamo add_to_waitlist
in eat_at_restaurant
, usiamo un
percorso relativo. Il percorso inizia con front_of_house
, il nome del modulo
definito allo stesso livello dell'albero dei moduli di eat_at_restaurant
. Qui l'equivalente nel filesystem sarebbe usare il percorso
front_of_house/hosting/add_to_waitlist
. Iniziare con un nome di modulo significa
che il percorso è relativo.
Scegliere se utilizzare un percorso relativo o assoluto è una decisione che prenderai
in base al tuo progetto, e dipende dal fatto che è più probabile che tu sposti il
codice di definizione dell'elemento separatamente o insieme al codice che utilizza
l'elemento. Ad esempio, se spostassimo il modulo front_of_house
e la
funzione eat_at_restaurant
in un modulo chiamato customer_experience
, dovremmo
aggiornare il percorso assoluto a add_to_waitlist
, ma il percorso relativo
sarebbe ancora valido. Tuttavia, se spostassimo la funzione eat_at_restaurant
separatamente in un modulo chiamato dining
, il percorso assoluto alla chiamata
di add_to_waitlist
rimarrebbe lo stesso, ma il percorso relativo dovrebbe essere
aggiornato. La nostra preferenza in generale è di specificare percorsi assoluti perché è
più probabile che vogliamo spostare le definizioni di codice e le chiamate degli elementi
indipendentemente l'una dall'altra.
Proviamo a compilare Listing 7-3 e scopriamo perché non si compilerà ancora! Gli errori che otteniamo sono mostrati in Listing 7-4.
$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: module `hosting` is private
--> src/lib.rs:9:28
|
9 | crate::front_of_house::hosting::add_to_waitlist();
| ^^^^^^^ private module
|
note: the module `hosting` is defined here
--> src/lib.rs:2:5
|
2 | mod hosting {
| ^^^^^^^^^^^
error[E0603]: module `hosting` is private
--> src/lib.rs:12:21
|
12 | front_of_house::hosting::add_to_waitlist();
| ^^^^^^^ private module
|
note: the module `hosting` is defined here
--> src/lib.rs:2:5
|
2 | mod hosting {
| ^^^^^^^^^^^
For more information about this error, try `rustc --explain E0603`.
error: could not compile `restaurant` due to 2 previous errors
I messaggi di errore dicono che il modulo hosting
è privato. In altre parole, abbiamo
i percorsi corretti per il modulo hosting
e la funzione add_to_waitlist
,
ma Rust non ci permetterà di usarli poiché non ha accesso alle sezioni
private. In Rust, tutti gli elementi (funzioni, metodi, struct, enum,
moduli e costanti) sono privati per impostazione predefinita nei moduli parent. Se vuoi
rendere un elemento come una funzione o una struct privato, lo metti in un modulo.
Gli elementi in un modulo parent non possono utilizzare gli elementi privati all'interno dei moduli child, ma gli elementi nei moduli child possono utilizzare gli elementi nei loro moduli ancestor. Questo è perché i moduli child avvolgono e nascondono i loro dettagli di implementazione, ma i moduli child possono vedere il contesto in cui sono definiti. Per continuare con il nostro metafora, pensa alle regole di privacy come all'ufficio amministrativo di un ristorante: quello che succede lì è privato per i clienti del ristorante, ma i manager dell'ufficio possono vedere e fare tutto nel ristorante che gestiscono.
Rust ha scelto di far funzionare il sistema di moduli in questo modo in modo che nascondere i dettagli interni
dell'implementazione sia l'impostazione predefinita. In questo modo, sai quali parti del
codice interno puoi cambiare senza rompere il codice esterno. Tuttavia, Rust ti dà la possibilità
di esporre le parti interne del codice dei moduli child ai moduli ancestor esterni
usando la parola chiave pub
per rendere un elemento pubblico.
Esposizione dei Percorsi con la parola chiave pub
Torniamo all'errore nella lista 7-4 che ci diceva che il modulo hosting
è
privato. Vogliamo che la funzione eat_at_restaurant
nel modulo parent abbia
accesso alla funzione add_to_waitlist
nel modulo child, quindi contrassegniamo il
modulo hosting
con la parola chiave pub
, come mostrato in Listing 7-5.
Nome del file: src/lib.rs
mod front_of_house {
pub mod hosting {
fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
Sfortunatamente, il codice nella lista 7-5 genera ancora errori del compilatore, come mostrato nella lista 7-6.
$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
error[E0603]: function `add_to_waitlist` is private
--> src/lib.rs:9:37
|
9 | crate::front_of_house::hosting::add_to_waitlist();
| ^^^^^^^^^^^^^^^ private function
|
note: the function `add_to_waitlist` is defined here
--> src/lib.rs:3:9
|
3 | fn add_to_waitlist() {}
| ^^^^^^^^^^^^^^^^^^^^
error[E0603]: function `add_to_waitlist` is private
--> src/lib.rs:12:30
|
12 | front_of_house::hosting::add_to_waitlist();
| ^^^^^^^^^^^^^^^ private function
|
note: the function `add_to_waitlist` is defined here
--> src/lib.rs:3:9
|
3 | fn add_to_waitlist() {}
| ^^^^^^^^^^^^^^^^^^^^
For more information about this error, try `rustc --explain E0603`.
error: could not compile `restaurant` due to 2 previous errors
Cosa è successo? Aggiungere la parola chiave pub
davanti a mod hosting
rende il
modulo pubblico. Con questa modifica, se possiamo accedere a front_of_house
, possiamo
accedere a hosting
. Ma i contenuti di hosting
sono ancora privati; rendere il
modulo pubblico non rende i suoi contenuti pubblici. La parola chiave pub
su un modulo
permette solo al codice nei suoi moduli ancestor di riferirsi ad esso, non di accedere
al suo codice interno. Poiché i moduli sono contenitori, non c'è molto che possiamo fare
rendendo solo il modulo pubblico; dobbiamo andare oltre e scegliere di rendere uno o più
degli elementi all'interno del modulo pubblici.
Gli errori nella lista 7-6 dicono che la funzione add_to_waitlist
è privata.
Le regole di privacy si applicano a struct, enum, funzioni e metodi così come
ai moduli.
Facciamo anche la funzione add_to_waitlist
pubblica aggiungendo la parola
chiave pub
prima della sua definizione, come nella lista 7-7.
Nome del file: src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}
Ora il codice si compilerà! Per capire perché l'aggiunta della parola chiave pub
ci permette di
usare questi percorsi in eat_at_restaurant
rispetto alle regole di privacy, diamo un'occhiata
ai percorsi assoluti e relativi.
Nel percorso assoluto, partiamo da crate
, la radice dell'albero dei moduli del nostro crate.
Il modulo front_of_house
è definito nella radice del crate. Anche se
front_of_house
non è pubblico, poiché la funzione eat_at_restaurant
è
definita nello stesso modulo di front_of_house
(cioè, eat_at_restaurant
e front_of_house
sono fratelli), possiamo fare riferimento a front_of_house
da
eat_at_restaurant
. Successivamente c'è il modulo hosting
contrassegnato con pub
. Possiamo
accedere al modulo parent di hosting
, quindi possiamo accedere a hosting
. Infine, la
funzione add_to_waitlist
è contrassegnata con pub
e possiamo accedere al suo modulo parent, quindi
questa chiamata di funzione funziona!
Nel percorso relativo, la logica è la stessa del percorso assoluto tranne per il
primo passo: piuttosto che iniziare dalla radice del crate, il percorso inizia da
front_of_house
. Il modulo front_of_house
è definito all'interno dello stesso modulo
di eat_at_restaurant
, quindi il percorso relativo che inizia dal modulo in cui
eat_at_restaurant
è definito funziona. Poi, poiché hosting
e
add_to_waitlist
sono contrassegnati con pub
, il resto del percorso funziona, e
questa chiamata di funzione è valida!
Se hai intenzione di condividere il tuo crate di libreria in modo che altri progetti possano utilizzare il tuo codice, la tua API pubblica è il tuo contratto con gli utenti del tuo crate che determina come possono interagire con il tuo codice. Ci sono molte considerazioni sulla gestione delle modifiche alla tua API pubblica per rendere più facile per le persone dipendere dal tuo crate. Queste considerazioni sono fuori dal campo di applicazione di questo libro; se sei interessato a questo argomento, consulta [Le Linee Guida API di Rust][api-guidelines].
Le Migliori Pratiche per i Pacchetti con un Binario e una Libreria
Abbiamo menzionato che un pacchetto può contenere sia una radice del crate binario src/main.rs sia una radice del crate di libreria src/lib.rs, e che entrambi i crate avranno il nome del pacchetto per impostazione predefinita. Tipicamente, i pacchetti con questo schema di contenere sia una libreria che un crate binario avranno solo il codice necessario nel crate binario per iniziare un eseguibile che chiama il codice all'interno del crate di libreria. Questo permette ad altri progetti di beneficiare della maggior parte della funzionalità che il pacchetto fornisce poiché il codice del crate di libreria può essere condiviso.
L'albero dei moduli dovrebbe essere definito in src/lib.rs. Poi, qualsiasi elemento pubblico può essere usato nel crate binario iniziando i percorsi con il nome del pacchetto. Il crate binario diventa un utente del crate di libreria proprio come farebbe un crate completamente esterno: può solo usare l'API pubblica. Questo ti aiuta a progettare una buona API; non solo sei l'autore, sei anche un cliente!
Nel [Capitolo 12][ch12], dimostreremo questa pratica organizzativa con un programma da linea di comando che conterrà sia un crate binario che un crate di libreria.
Iniziare Percorsi Relativi con super
Possiamo costruire percorsi relativi che iniziano nel modulo parent, piuttosto che
nel modulo corrente o nella radice del crate, utilizzando super
all'inizio del
percorso. Questo è come iniziare un percorso filesystem con la sintassi ..
. Usare
super
ci permette di fare riferimento a un elemento che sappiamo essere nel modulo parent,
il che può rendere più facile la riorganizzazione dell'albero dei moduli quando il modulo è strettamente
relato al parent ma il parent potrebbe essere spostato altrove nell'albero dei moduli un giorno.
Considera il codice in Listing 7-8 che modella la situazione in cui uno chef
corregge un ordine errato e lo porta personalmente al cliente. La
funzione fix_incorrect_order
definita nel modulo back_of_house
chiama la
funzione deliver_order
definita nel modulo parent specificando il percorso a
deliver_order
, iniziando con super
.
Nome del file: src/lib.rs
fn deliver_order() {}
mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::deliver_order();
}
fn cook_order() {}
}
La funzione fix_incorrect_order
si trova nel modulo back_of_house
, quindi possiamo
usare super
per andare al modulo parent di back_of_house
, che in questo caso
è crate
, la radice. Da lì, cerchiamo deliver_order
e lo troviamo.
Successo! Pensiamo che il modulo back_of_house
e la funzione deliver_order
siano probabilmente destinati a rimanere nella stessa relazione tra di loro e a
essere spostati insieme se un giorno decidessimo di riorganizzare l'albero dei moduli
del crate. Pertanto, abbiamo usato super
in modo da avere meno luoghi in cui aggiornare
il codice in futuro se questo codice venisse spostato in un altro modulo.
Rendere Pubblici Structs e Enums
Possiamo anche usare pub
per designare structs e enums come pubblici, ma ci
sono alcuni dettagli aggiuntivi nell'uso di pub
con structs e enums. Se usiamo pub
prima di una definizione struct, rendiamo la struct pubblica, ma i campi della struct
saranno ancora privati. Possiamo rendere ogni campo pubblico o meno caso per caso. Nella
lista 7-9, abbiamo definito una struct pubblica back_of_house::Breakfast
con un campo toast
pubblico ma un campo seasonal_fruit
privato. Questo modella
il caso in un ristorante in cui il cliente può scegliere il tipo di pane che
accompagna un pasto, ma il cuoco decide quale frutta accompagna il pasto in base a ciò che è
di stagione e disponibile in magazzino. La frutta disponibile cambia rapidamente, quindi
i clienti non possono scegliere la frutta o nemmeno vedere quale frutta riceveranno.
Nome del file: src/lib.rs
mod back_of_house {
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast: &str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
pub fn eat_at_restaurant() {
// Order a breakfast in the summer with Rye toast
let mut meal = back_of_house::Breakfast::summer("Rye");
// Change our mind about what bread we'd like
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
// The next line won't compile if we uncomment it; we're not allowed
// to see or modify the seasonal fruit that comes with the meal
// meal.seasonal_fruit = String::from("blueberries");
}
Poiché il campo toast
nella struct back_of_house::Breakfast
è pubblico,
in eat_at_restaurant
possiamo scrivere e leggere il campo toast
usando la notazione col
punto. Nota che non possiamo usare il campo seasonal_fruit
in
eat_at_restaurant
, perché seasonal_fruit
è privato. Prova a togliere il commento alla
linea che modifica il valore del campo seasonal_fruit
per vedere quale errore ottieni!
Nota anche che poiché back_of_house::Breakfast
ha un campo privato, la
struct deve fornire una funzione associata pubblica che costruisca un'istanza di Breakfast
(l'abbiamo chiamata summer
qui). Se Breakfast
non avesse una tale funzione, non
potremmo creare un'istanza di Breakfast
in eat_at_restaurant
perché non
potremmo impostare il valore del campo privato seasonal_fruit
in eat_at_restaurant
.
Al contrario, se rendiamo un enum pubblico, tutte le sue varianti diventano pubbliche. Abbiamo
bisogno solo della pub
davanti alla parola chiave enum
, come mostrato in Listing 7-10.
Nome del file: src/lib.rs
rust
rust,noplayground
mod back_of_house {
pub enum Appetizer {
Soup,
Salad,
}
}
pub fn eat_at_restaurant() { let order1 = back_of_house::Appetizer::Soup; let order2 = back_of_house::Appetizer::Salad; }
<span class="caption">Listing 7-10: Designare un enum come pubblico rende tutte le sue
varianti pubbliche</span>
Poiché abbiamo reso l'enum `Appetizer` pubblico, possiamo usare le varianti `Soup` e `Salad` in `eat_at_restaurant`.
Gli enum non sono molto utili a meno che le loro varianti non siano pubbliche; sarebbe fastidioso
dover annotare tutte le varianti enum con `pub` in ogni caso, quindi l'impostazione predefinita per le varianti enum è di essere pubblica. Le struct sono spesso utili anche senza che i loro campi siano pubblici, quindi i campi delle struct seguono la regola generale di essere privati per impostazione predefinita, a meno che non siano annotati con `pub`.
C'è un'altra situazione che coinvolge `pub` che non abbiamo coperto, ed è la nostra ultima funzione del sistema dei moduli: la parola chiave `use`. Tratteremo `use` da sola prima e poi mostreremo come combinare `pub` e `use`.
[pub]: ch07-03-paths-for-referring-to-an-item-in-the-module-tree.html#exposing-paths-with-the-pub-keyword
[api-guidelines]: https://rust-lang.github.io/api-guidelines/
[ch12]: ch12-00-an-io-project.html
Portare i Percorsi nello Scope con la Parola Chiave use
Scrivere i percorsi per chiamare le funzioni può sembrare scomodo e ripetitivo. Nella Listing 7-7, sia che scegliamo il percorso assoluto o relativo per la funzione add_to_waitlist
, ogni volta che vogliamo chiamare add_to_waitlist
dobbiamo specificare anche front_of_house
e hosting
. Fortunatamente, c'è un modo per semplificare questo processo: possiamo creare una scorciatoia per un percorso con la parola chiave use
una volta, e poi usare il nome più corto ovunque nello scope.
Nella Listing 7-11, portiamo il modulo crate::front_of_house::hosting
nello scope della funzione eat_at_restaurant
così dobbiamo solo specificare hosting::add_to_waitlist
per chiamare la funzione add_to_waitlist
in eat_at_restaurant
.
Filename: src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
Aggiungere use
e un percorso nello scope è simile a creare un collegamento simbolico nel filesystem. Aggiungendo use crate::front_of_house::hosting
nel crate root, hosting
è ora un nome valido in quello scope, proprio come se il modulo hosting
fosse stato definito nel crate root. I percorsi portati nello scope con use
controllano anche la privacy, come qualsiasi altro percorso.
Nota che use
crea solo la scorciatoia per lo specifico scope in cui use
si verifica. La Listing 7-12 sposta la funzione eat_at_restaurant
in un nuovo modulo figlio chiamato customer
, che è poi un scope diverso rispetto alla dichiarazione use
, quindi il corpo della funzione non compila.
Filename: src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
mod customer {
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
}
L'errore del compilatore mostra che la scorciatoia non si applica più nel modulo customer
:
$ cargo build
Compiling restaurant v0.1.0 (file:///projects/restaurant)
warning: unused import: `crate::front_of_house::hosting`
--> src/lib.rs:7:5
|
7 | use crate::front_of_house::hosting;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error[E0433]: failed to resolve: use of undeclared crate or module `hosting`
--> src/lib.rs:11:9
|
11 | hosting::add_to_waitlist();
| ^^^^^^^ use of undeclared crate or module `hosting`
For more information about this error, try `rustc --explain E0433`.
warning: `restaurant` (lib) generated 1 warning
error: could not compile `restaurant` due to previous error; 1 warning emitted
Nota che c'è anche un avviso che il use
non è più utilizzato nel suo scope! Per risolvere questo problema, sposta il use
anche all'interno del modulo customer
, o riferisciti alla scorciatoia nel modulo padre con super::hosting
all'interno del modulo figlio customer
.
Creare Percorsi use
Idiomatici
Nella Listing 7-11, potresti esserti chiesto perché abbiamo specificato use crate::front_of_house::hosting
e poi chiamato hosting::add_to_waitlist
in eat_at_restaurant
, piuttosto che specificare il percorso use
fino alla funzione add_to_waitlist
per ottenere lo stesso risultato, come nella Listing 7-13.
Filename: src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting::add_to_waitlist;
pub fn eat_at_restaurant() {
add_to_waitlist();
}
Anche se sia la Listing 7-11 che la Listing 7-13 raggiungono lo stesso compito, la Listing 7-11 è il modo idiomatico di portare una funzione nello scope con use
. Portare il modulo genitore della funzione nello scope con use
significa che dobbiamo specificare il modulo genitore quando chiamiamo la funzione. Specificare il modulo genitore quando chiamiamo la funzione rende chiaro che la funzione non è definita localmente pur minimizzando la ripetizione del percorso completo. Il codice nella Listing 7-13 non è chiaro su dove sia definita add_to_waitlist
.
D'altra parte, quando si portano negli scope struct, enum, e altri elementi con use
, è idiomatico specificare il percorso completo. La Listing 7-14 mostra il modo idiomatico di portare lo struct HashMap
della libreria standard nello scope di un crate binario.
Filename: src/main.rs
use std::collections::HashMap; fn main() { let mut map = HashMap::new(); map.insert(1, 2); }
Non c'è una forte ragione dietro questo idioma: è solo la convenzione che è emersa, e la gente è abituata a leggere e scrivere codice Rust in questo modo.
L'eccezione a questo idioma è se stiamo portando due elementi con lo stesso nome nello scope con dichiarazioni use
, perché Rust non lo permette. La Listing 7-15 mostra come portare due tipi Result
nello scope che hanno lo stesso nome ma moduli genitori diversi, e come riferirsi a loro.
Filename: src/lib.rs
use std::fmt;
use std::io;
fn function1() -> fmt::Result {
// --snip--
Ok(())
}
fn function2() -> io::Result<()> {
// --snip--
Ok(())
}
Come puoi vedere, usare i moduli genitori distingue i due tipi Result
. Se invece specificassimo use std::fmt::Result
e use std::io::Result
, avremmo due tipi Result
nello stesso scope, e Rust non saprebbe a quale ci riferiamo quando usiamo Result
.
Fornire Nuovi Nomi con la Parola Chiave as
C'è un'altra soluzione al problema di portare due tipi con lo stesso nome nello stesso scope con use
: dopo il percorso, possiamo specificare as
e un nuovo nome locale, o alias, per il tipo. La Listing 7-16 mostra un altro modo di scrivere il codice nella Listing 7-15 rinominando uno dei due tipi Result
usando as
.
Filename: src/lib.rs
use std::fmt::Result;
use std::io::Result as IoResult;
fn function1() -> Result {
// --snip--
Ok(())
}
fn function2() -> IoResult<()> {
// --snip--
Ok(())
}
Nella seconda dichiarazione use
, abbiamo scelto il nuovo nome IoResult
per il tipo std::io::Result
, che non confliggerà con il Result
da std::fmt
che abbiamo anche portato nello scope. La Listing 7-15 e la Listing 7-16 sono considerate idiomatiche, quindi la scelta è tua!
Riesportare Nomi con pub use
Quando portiamo un nome nello scope con la parola chiave use
, il nome disponibile nel nuovo scope è privato. Per permettere al codice che chiama il nostro codice di riferirsi a quel nome come se fosse stato definito nello scope del codice chiamante, possiamo combinare pub
e use
. Questa tecnica si chiama riesportazione perché stiamo portando un elemento nello scope ma rendendolo anche disponibile per essere portato nello scope di altri.
La Listing 7-17 mostra il codice nella Listing 7-11 con la dichiarazione use
nel modulo root cambiata in pub use
.
Filename: src/lib.rs
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
Prima di questa modifica, il codice esterno avrebbe dovuto chiamare la funzione add_to_waitlist
usando il percorso restaurant::front_of_house::hosting::add_to_waitlist()
, che avrebbe anche richiesto che il modulo front_of_house
fosse contrassegnato come pub
. Ora che questo pub use
ha riesportato il modulo hosting
dal modulo root, il codice esterno può usare il percorso restaurant::hosting::add_to_waitlist()
invece.
La riesportazione è utile quando la struttura interna del tuo codice è diversa da come i programmatori che chiamano il tuo codice penserebbero al dominio. Ad esempio, in questa metafora del ristorante, le persone che gestiscono il ristorante pensano a "front of house" e "back of house". Ma i clienti che visitano un ristorante probabilmente non pensano alle parti del ristorante in questi termini. Con pub use
, possiamo scrivere il nostro codice con una struttura ma esporne un'altra. Farlo rende la nostra libreria ben organizzata per i programmatori che lavorano sulla libreria e per quelli che chiamano la libreria. Guarderemo un altro esempio di pub use
e come influisce sulla documentazione del tuo crate nella sezione “Esportare una API Pubblica Conveniente con pub use
” del Capitolo 14.
Usare Pacchetti Esterni
Nel Capitolo 2, abbiamo programmato un progetto di gioco d'azzardo che usava un pacchetto esterno chiamato rand
per ottenere numeri casuali. Per usare rand
nel nostro progetto, abbiamo aggiunto questa linea a Cargo.toml:
Filename: Cargo.toml
rand = "0.8.5"
Aggiungere rand
come dipendenza in Cargo.toml dice a Cargo di scaricare il pacchetto rand
e tutte le dipendenze da crates.io e rendere rand
disponibile per il nostro progetto.
Poi, per portare le definizioni di rand
nello scope del nostro pacchetto, abbiamo aggiunto una linea use
che inizia con il nome del crate, rand
, e abbiamo elencato gli elementi che volevamo portare nello scope. Ricorda che nella sezione “Generare un Numero Casuale” nel Capitolo 2, abbiamo portato nello scope il Rng
trait e chiamato la funzione rand::thread_rng
:
use std::io;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
I membri della comunità Rust hanno reso disponibili molti pacchetti su crates.io, e portarli nel tuo pacchetto comporta questi stessi passaggi: elencarli nel file Cargo.toml del tuo pacchetto e usare use
per portare gli elementi dai loro crate nello scope.
Nota che la libreria standard std
è anche un crate esterno al nostro pacchetto. Poiché la libreria standard viene fornita con il linguaggio Rust, non dobbiamo modificare Cargo.toml per includere std
. Ma dobbiamo riferirci a essa con use
per portare elementi da lì nello scope del nostro pacchetto. Ad esempio, con HashMap
useremmo questa linea:
#![allow(unused)] fn main() { use std::collections::HashMap; }
Questo è un percorso assoluto che inizia con std
, il nome del crate della libreria standard.
Usare Percorsi Annidati per Ripulire Lunghe Liste use
Se stiamo usando più elementi definiti nello stesso crate o nello stesso modulo, elencare ogni elemento su una propria linea può occupare molto spazio verticale nei nostri file. Ad esempio, queste due dichiarazioni use
che avevamo nel gioco d'azzardo nella Listing 2-4 portano elementi da std
nello scope:
Filename: src/main.rs
use rand::Rng;
// --snip--
use std::cmp::Ordering;
use std::io;
// --snip--
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
Invece, possiamo usare percorsi annidati per portare gli stessi elementi nello scope in una sola linea. Facciamo questo specificando la parte comune del percorso, seguita da due punti doppi, e poi parentesi graffe attorno a un elenco delle parti dei percorsi che differiscono, come mostrato nella Listing 7-18.
Filename: src/main.rs
use rand::Rng;
// --snip--
use std::{cmp::Ordering, io};
// --snip--
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = guess.trim().parse().expect("Please type a number!");
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
Nei programmi più grandi, portare molti elementi nello scope dallo stesso crate o modulo usando percorsi annidati può ridurre di molto il numero di dichiarazioni use
separate necessarie!
Possiamo usare un percorso annidato a qualsiasi livello in un percorso, che è utile quando si combinano due dichiarazioni use
che condividono un sotto-percorso. Ad esempio, la Listing 7-19 mostra due dichiarazioni use
: una che porta std::io
nello scope e una che porta std::io::Write
nello scope.
Filename: src/lib.rs
use std::io;
use std::io::Write;
La parte comune di questi due percorsi è std::io
, ed è il percorso completo. Per unire questi due percorsi in una dichiarazione use
, possiamo usare self
nel percorso annidato, come mostrato nella Listing 7-20.
Filename: src/lib.rs
use std::io::{self, Write};
Questa linea porta std::io
e std::io::Write
nello scope.
L'Operatore Glob
Se vogliamo portare tutti gli elementi pubblici definiti in un percorso nello scope, possiamo specificare quel percorso seguito dall'operatore glob *
:
#![allow(unused)] fn main() { use std::collections::*; }
Questa dichiarazione use
porta tutti gli elementi pubblici definiti in std::collections
nello scope corrente. Fai attenzione quando usi l'operatore glob! Glob può rendere più difficile capire quali nomi sono nello scope e dove è stato definito un nome usato nel tuo programma.
L'operatore glob è spesso usato quando si scrivono test per portare tutto ciò che si trova sotto test nel modulo tests
; ne parleremo nella sezione “Come Scrivere Test” nel Capitolo 11. L'operatore glob è talvolta usato anche come parte del pattern prelude: vedi la documentazione della libreria standard per ulteriori informazioni su questo pattern.
Separazione dei Moduli in File Diversi
Finora, tutti gli esempi in questo capitolo hanno definito più moduli in un unico file. Quando i moduli diventano grandi, potresti voler spostare le loro definizioni in un file separato per rendere il codice più facile da navigare.
Ad esempio, iniziamo dal codice nella Listing 7-17 che aveva più moduli del ristorante. Estrarremo i moduli in file invece di avere tutti i moduli definiti nel file radice del crate. In questo caso, il file radice del crate è src/lib.rs, ma questa procedura funziona anche con i binary crates il cui file radice del crate è src/main.rs.
Per prima cosa estrarremo il modulo front_of_house
nel suo file. Rimuovi il codice all'interno delle parentesi graffe per il modulo front_of_house
, lasciando solo la dichiarazione mod front_of_house;
in modo che src/lib.rs contenga il codice mostrato nella Listing 7-21. Nota che questo non compilerà finché non creeremo il file src/front_of_house.rs nella Listing 7-22.
Nome del file: src/lib.rs
mod front_of_house;
pub use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
}
Successivamente, posiziona il codice che era nelle parentesi graffe in un nuovo file chiamato src/front_of_house.rs, come mostrato nella Listing 7-22. Il compilatore sa di cercare in questo file perché ha incontrato la dichiarazione del modulo nel crate root con il nome front_of_house
.
Nome del file: src/front_of_house.rs
pub mod hosting {
pub fn add_to_waitlist() {}
}
Nota che hai bisogno di caricare un file usando una dichiarazione mod
una sola volta nel tuo albero dei moduli. Una volta che il compilatore sa che il file fa parte del progetto (e sa dove si trova il codice nell'albero dei moduli grazie a dove hai posizionato l'istruzione mod
), altri file nel tuo progetto dovrebbero fare riferimento al codice del file caricato usando un path dove è stato dichiarato, come trattato nella sezione “Path per Fare Riferimento a un Elemento nell'Albero dei Moduli”. In altre parole, mod
non è un'operazione di "inclusione" che potresti aver visto in altri linguaggi di programmazione.
Successivamente, estrarremo il modulo hosting
nel suo file. Il processo è un po' diverso perché hosting
è un modulo figlio di front_of_house
, non del modulo root. Posizioneremo il file per hosting
in una nuova directory che verrà chiamata con il nome dei suoi antenati nell'albero dei moduli, in questo caso src/front_of_house.
Per cominciare a spostare hosting
, cambiamo src/front_of_house.rs in modo che contenga solo la dichiarazione del modulo hosting
:
Nome del file: src/front_of_house.rs
pub mod hosting;
Quindi creiamo una directory src/front_of_house e un file hosting.rs per contenere le definizioni fatte nel modulo hosting
:
Nome del file: src/front_of_house/hosting.rs
pub fn add_to_waitlist() {}
Se invece mettessimo hosting.rs nella directory src, il compilatore si aspetterebbe che il codice di hosting.rs sia in un modulo hosting
dichiarato nel crate root, e non dichiarato come figlio del modulo front_of_house
. Le regole del compilatore su quali file controllare per il codice di quali moduli fanno sì che le directory e i file corrispondano più strettamente all'albero dei moduli.
Percorsi Alternativi dei File
Finora abbiamo coperto i percorsi dei file più idiomatici che il compilatore Rust usa, ma Rust supporta anche uno stile più vecchio di percorso dei file. Per un modulo chiamato
front_of_house
dichiarato nel crate root, il compilatore cercherà il codice del modulo in:
- src/front_of_house.rs (ciò che abbiamo trattato)
- src/front_of_house/mod.rs (stile più vecchio, percorso ancora supportato)
Per un modulo chiamato
hosting
che è un sottomodulo difront_of_house
, il compilatore cercherà il codice del modulo in:
- src/front_of_house/hosting.rs (ciò che abbiamo trattato)
- src/front_of_house/hosting/mod.rs (stile più vecchio, percorso ancora supportato)
Se usi entrambi gli stili per lo stesso modulo, otterrai un errore del compilatore. Usare un mix di entrambi gli stili per moduli diversi nello stesso progetto è permesso, ma potrebbe essere confuso per le persone che navigano nel tuo progetto.
Il principale svantaggio dello stile che usa file chiamati mod.rs è che il tuo progetto può finire con molti file chiamati mod.rs, il che può diventare confuso quando li hai aperti nel tuo editor allo stesso tempo.
Abbiamo spostato il codice di ciascun modulo in un file separato, e l'albero dei moduli rimane lo stesso. Le chiamate di funzione in eat_at_restaurant
funzioneranno senza alcuna modifica, anche se le definizioni risiedono in file diversi. Questa tecnica ti consente di spostare i moduli in nuovi file man mano che crescono di dimensioni.
Nota che l'istruzione pub use crate::front_of_house::hosting
in
src/lib.rs non è cambiata, né use
ha alcun impatto su quali file vengono compilati come parte del crate. La parola chiave mod
dichiara i moduli e Rust cerca in un file con lo stesso nome del modulo il codice che va in quel modulo.
Sommario
Rust ti permette di suddividere un package in più crates e un crate in moduli in modo da poter fare riferimento agli elementi definiti in un modulo da un altro modulo. Puoi farlo specificando percorsi assoluti o relativi. Questi percorsi possono essere portati in scope con un'istruzione use
in modo da poter usare un percorso più breve per usi multipli dell'elemento in quel scope. Il codice del modulo è privato per impostazione predefinita, ma puoi rendere le definizioni pubbliche aggiungendo la parola chiave pub
.
Nel prossimo capitolo, esamineremo alcune strutture di dati della collezione nella libreria standard che puoi usare nel tuo codice organizzato con ordine.
Collezioni Comuni
La libreria standard di Rust include una serie di strutture dati molto utili chiamate collezioni. La maggior parte degli altri tipi di dati rappresenta un valore specifico, ma le collezioni possono contenere più valori. A differenza dei tipi di array e tuple incorporati, i dati a cui queste collezioni puntano sono memorizzati nello heap, il che significa che la quantità di dati non deve essere conosciuta al momento della compilazione e può crescere o diminuire mentre il programma è in esecuzione. Ogni tipo di collezione ha capacità e costi differenti, e scegliere quella appropriata per la tua situazione corrente è una competenza che svilupperai nel tempo. In questo capitolo, discuteremo tre collezioni che sono molto utilizzate nei programmi Rust:
- Un vector ti consente di memorizzare un numero variabile di valori uno accanto all'altro.
- Una string è una collezione di caratteri. Abbiamo menzionato il tipo
String
in precedenza, ma in questo capitolo ne parleremo in dettaglio. - Un hash map ti permette di associare un valore a una chiave specifica. È un'implementazione particolare della struttura dati più generica chiamata map.
Per saperne di più sugli altri tipi di collezioni fornite dalla libreria standard, consulta la documentazione.
Discuteremo come creare e aggiornare vector, string e hash map, nonché cosa rende ciascuno di essi speciale.
Memorizzazione di elenchi di valori con Vectors
Il primo tipo di collezione che vedremo è Vec<T>
, anche noto come vector. I Vectors ti permettono di memorizzare più di un valore in una singola struttura di dati che mette tutti i valori uno accanto all'altro in memoria. I Vectors possono memorizzare solo valori dello stesso tipo. Sono utili quando hai un elenco di elementi, come le righe di testo in un file o i prezzi degli articoli in un carrello della spesa.
Creazione di un nuovo Vector
Per creare un nuovo vector vuoto, chiamiamo la funzione Vec::new
, come mostrato nel Listing 8-1.
fn main() { let v: Vec<i32> = Vec::new(); }
Nota che qui abbiamo aggiunto un'annotazione di tipo. Poiché non stiamo inserendo valori in questo vector, Rust non sa che tipo di elementi intendiamo memorizzare. Questo è un punto importante. I Vectors sono implementati utilizzando i generici; vedremo come usare i generici con i tuoi tipi nel Capitolo 10. Per ora, sappi che il tipo Vec<T>
fornito dalla libreria standard può contenere qualsiasi tipo. Quando creiamo un vector per contenere un tipo specifico, possiamo specificare il tipo all'interno di parentesi angolari. Nel Listing 8-1, abbiamo detto a Rust che il Vec<T>
in v
conterrà elementi del tipo i32
.
Più spesso, creerai un Vec<T>
con valori iniziali e Rust dedurrà il tipo di valore che vuoi memorizzare, quindi raramente hai bisogno di fare questa annotazione di tipo. Rust fornisce convenientemente la macro vec!
, che creerà un nuovo vector che contiene i valori che gli dai. Il Listing 8-2 crea un nuovo Vec<i32>
che contiene i valori 1
, 2
e 3
. Il tipo di intero è i32
perché è il tipo di intero predefinito, come abbiamo discusso nella sezione “Data Types” del Capitolo 3.
fn main() { let v = vec![1, 2, 3]; }
Poiché abbiamo dato valori iniziali i32
, Rust può dedurre che il tipo di v
è Vec<i32>
, e l'annotazione di tipo non è necessaria. Successivamente vedremo come
modificare un vector.
Aggiornamento di un Vector
Per creare un vector e poi aggiungere elementi, possiamo usare il metodo push
,
come mostrato nel Listing 8-3.
fn main() { let mut v = Vec::new(); v.push(5); v.push(6); v.push(7); v.push(8); }
Come con qualsiasi variabile, se vogliamo essere in grado di cambiarne il valore, dobbiamo renderla mutabile usando la parola chiave mut
, come discusso nel Capitolo 3. I numeri
che mettiamo dentro sono tutti di tipo i32
, e Rust lo deduce dai dati, quindi non
abbiamo bisogno dell'annotazione Vec<i32>
.
Lettura degli elementi dei Vectors
Ci sono due modi per fare riferimento a un valore memorizzato in un vector: tramite indice o utilizzando il metodo get
. Nei seguenti esempi, abbiamo annotato i tipi dei
valori che vengono restituiti da queste funzioni per maggiore chiarezza.
Il Listing 8-4 mostra entrambi i metodi di accesso a un valore in un vector, con sintassi di indicizzazione e il metodo get
.
fn main() { let v = vec![1, 2, 3, 4, 5]; let third: &i32 = &v[2]; println!("The third element is {third}"); let third: Option<&i32> = v.get(2); match third { Some(third) => println!("The third element is {third}"), None => println!("There is no third element."), } }
Nota alcuni dettagli qui. Usiamo il valore di indice 2
per ottenere il terzo elemento
perché i vectors sono indicizzati per numero, iniziando da zero. Usare &
e []
ci dà un riferimento all'elemento al valore di indice. Quando usiamo il metodo get
con l'indice passato come argomento, otteniamo un Option<&T>
che possiamo
usare con match
.
Rust fornisce questi due modi di fare riferimento a un elemento in modo che tu possa scegliere come deve comportarsi il programma quando provi a usare un valore di indice fuori dal range degli elementi esistenti. Come esempio, vediamo cosa succede quando abbiamo un vector di cinque elementi e poi proviamo ad accedere a un elemento all'indice 100 con ciascuna tecnica, come mostrato nel Listing 8-5.
fn main() { let v = vec![1, 2, 3, 4, 5]; let does_not_exist = &v[100]; let does_not_exist = v.get(100); }
Quando eseguiamo questo codice, il primo metodo []
farà andare il programma in panic
perché fa riferimento a un elemento inesistente. Questo metodo è meglio utilizzato quando vuoi che il tuo programma si blocchi se c'è un tentativo di accesso a un elemento oltre la fine del vector.
Quando il metodo get
riceve un indice che è fuori dal vector, restituisce None
senza andare in panic. Utilizzeresti questo metodo se l'accesso a un elemento
oltre il range del vector può accadere occasionalmente in circostanze normali. Il tuo codice avrà quindi la logica per gestire l'avere Some(&element)
o None
, come discusso nel Capitolo 6. Per esempio, l'indice potrebbe provenire da una persona che inserisce
un numero. Se inseriscono accidentalmente un numero troppo grande e il programma ottiene un valore None
, potresti dire all'utente quanti elementi ci sono nel vector corrente e dargli un'altra possibilità di inserire un valore valido. Questo sarebbe più amichevole per l'utente rispetto a far bloccare il programma per un errore di battitura!
Quando il programma ha un riferimento valido, il borrow checker impone le regole di ownership e borrowing (coperte nel Capitolo 4) per garantire che questo riferimento e qualsiasi altro riferimento ai contenuti del vector rimangano validi. Ricorda la regola che dice che non puoi avere riferimenti mutabili e immutabili nello stesso scope. Questa regola si applica nel Listing 8-6, dove teniamo un riferimento immutabile al primo elemento in un vector e proviamo ad aggiungere un elemento alla fine. Questo programma non funzionerà se proviamo anche a fare riferimento a quell'elemento più tardi nella funzione.
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0];
v.push(6);
println!("The first element is: {first}");
}
Compilare questo codice risulterà in questo errore:
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:6:5
|
4 | let first = &v[0];
| - immutable borrow occurs here
5 |
6 | v.push(6);
| ^^^^^^^^^ mutable borrow occurs here
7 |
8 | println!("The first element is: {first}");
| ----- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `collections` due to previous error
Il codice nel Listing 8-6 potrebbe sembrare che dovrebbe funzionare: perché un riferimento al primo elemento dovrebbe preoccuparsi dei cambiamenti alla fine del vector? Questo errore è dovuto al modo in cui funzionano i vectors: poiché i vectors mettono i valori uno accanto all'altro in memoria, aggiungere un nuovo elemento alla fine del vector potrebbe richiedere l'allocazione di nuova memoria e la copia dei vecchi elementi nello spazio nuovo, se non c'è abbastanza spazio per mettere tutti gli elementi uno accanto all'altro dove il vector è attualmente memorizzato. In tal caso, il riferimento al primo elemento punterebbe a memoria deallocata. Le regole di borrowing impediscono ai programmi di trovarsi in quella situazione.
Nota: Per maggiori dettagli sull'implementazione del tipo
Vec<T>
, consulta “The Rustonomicon”.
Iterazione sui valori in un Vector
Per accedere a ogni elemento in un vector a turno, itereremmo attraverso tutti gli
elementi piuttosto che usare indici per accedervi uno alla volta. Il Listing 8-7 mostra come usare un ciclo for
per ottenere riferimenti immutabili a ciascun elemento in un vector di valori i32
e stamparli.
fn main() { let v = vec![100, 32, 57]; for i in &v { println!("{i}"); } }
Possiamo anche iterare sui riferimenti mutabili a ciascun elemento in un vector mutabile per apportare modifiche a tutti gli elementi. Il ciclo for
nel Listing 8-8
aggiungerà 50
a ciascun elemento.
fn main() { let mut v = vec![100, 32, 57]; for i in &mut v { *i += 50; } }
Per cambiare il valore a cui si riferisce il riferimento mutabile, dobbiamo usare
l'operatore di dereferenza *
per accedere al valore in i
prima di poter usare l'operatore +=
. Parleremo di più dell'operatore di dereferenza nella sezione “Following the
Pointer to the Value with the Dereference Operator” del Capitolo 15.
Iterare su un vector, sia in modo immutabile che mutabile, è sicuro grazie alle regole del borrow checker. Se tentassimo di inserire o rimuovere elementi nei corpi del ciclo for
nel Listing 8-7 e nel Listing 8-8, otterremmo un errore del compilatore simile a quello che abbiamo ottenuto con il codice nel Listing 8-6. Il riferimento al vector che il ciclo for
tiene impedisce la modifica simultanea dell'intero vector.
Uso di un Enum per memorizzare più tipi
I Vectors possono memorizzare solo valori dello stesso tipo. Questo può essere inconveniente; ci sono sicuramente casi d'uso in cui è necessario memorizzare un elenco di elementi di tipi diversi. Fortunatamente, i varianti di un enum sono definiti sotto lo stesso tipo di enum, quindi quando abbiamo bisogno di un tipo per rappresentare elementi di tipi diversi, possiamo definire e usare un enum!
Per esempio, supponiamo di voler ottenere valori da una riga in un foglio di calcolo in cui alcune delle colonne della riga contengono interi, alcuni numeri a virgola mobile, e alcune stringhe. Possiamo definire un enum le cui varianti contengono i diversi tipi di valore, e tutte le varianti dell'enum saranno considerate dello stesso tipo: quello dell'enum. Poi possiamo creare un vector per contenere quell'enum e quindi, in ultima analisi, contenere tipi diversi. Abbiamo dimostrato questo nel Listing 8-9.
fn main() { enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; }
Rust ha bisogno di sapere quali tipi saranno nel vector al momento della compilazione
così sa esattamente quanta memoria sullo heap sarà necessaria per memorizzare ciascun elemento. Dobbiamo anche essere espliciti su quali tipi sono consentiti in questo vector.
Se Rust permettesse a un vector di contenere qualsiasi tipo, ci sarebbe la possibilità
che uno o più tipi causino errori con le operazioni eseguite sugli elementi del vector. Usare un enum più un'espressione match
significa che Rust assicurerà al momento della
compilazione che ogni caso possibile venga gestito, come discusso nel Capitolo 6.
Se non conosci l'insieme esaustivo di tipi che un programma otterrà al momento dell'esecuzione per memorizzare in un vector, la tecnica dell'enum non funzionerà. Invece, puoi usare un trait object, che copriremo nel Capitolo 17.
Ora che abbiamo discusso alcuni dei modi più comuni di usare i vectors, assicuriamoci di rivedere la documentazione dell'API per tutti i molti metodi utili definiti su Vec<T>
dalla libreria standard. Per esempio, oltre a push
, un metodo pop
rimuove e restituisce l'ultimo elemento.
Eliminazione di un Vector elimina i suoi elementi
Come qualsiasi altro struct
, un vector viene liberato quando esce dal suo scope,
come annotato nel Listing 8-10.
fn main() { { let v = vec![1, 2, 3, 4]; // do stuff with v } // <- v goes out of scope and is freed here }
Quando il vector viene eliminato, anche tutti i suoi contenuti vengono eliminati, significando che gli interi che contiene verranno puliti. Il borrow checker garantisce che eventuali riferimenti ai contenuti di un vector siano utilizzati solo mentre il vector stesso è valido.
Passiamo al prossimo tipo di collezione: String
!
Memorizzare Testo Codificato UTF-8 con Strings
Abbiamo parlato delle stringhe nel Capitolo 4, ma adesso le esamineremo più nel dettaglio. I nuovi Rustaceans trovano spesso difficoltà con le stringhe per una combinazione di tre ragioni: la propensione di Rust a esporre possibili errori, le stringhe essendo una struttura dati più complicata di quanto molti programmatori pensino, e UTF-8. Questi fattori si combinano in un modo che può sembrare difficile quando si proviene da altri linguaggi di programmazione.
Discutiamo delle stringhe nel contesto delle collezioni perché le stringhe sono implementate come una collezione di byte, oltre a metodi che forniscono funzionalità utili quando quei byte sono interpretati come testo. In questa sezione, parleremo delle operazioni su String
che ogni tipo di collezione ha, come creare, aggiornare e leggere. Discuteremo anche i modi in cui String
è diversa dalle altre collezioni, cioè come l'indicizzazione di una String
è complicata dalle differenze tra come le persone e i computer interpretano i dati String
.
Cos'è una String?
Per prima cosa definiremo cosa intendiamo per il termine stringa. Rust ha solo un tipo di stringa nel linguaggio base, che è lo string slice str
che solitamente si vede nella sua forma presa in prestito &str
. Nel Capitolo 4, abbiamo parlato delle string slices, che sono riferimenti ad alcuni dati di stringa codificati UTF-8 memorizzati altrove. I letterali di stringa, per esempio, sono memorizzati nel binario del programma e sono quindi string slices.
Il tipo String
, che è fornito dalla libreria standard di Rust piuttosto che codificato nel linguaggio base, è un tipo di stringa codificata UTF-8, cresciuta, mutabile, di proprietà. Quando i Rustaceans si riferiscono a “stringhe” in Rust, potrebbero riferirsi sia ai tipi String
sia allo string slice &str
, non solo a uno di questi tipi. Sebbene questa sezione sia in gran parte su String
, entrambi i tipi sono utilizzati ampiamente nella libreria standard di Rust, ed entrambe String
e string slices sono codificate UTF-8.
Creare una Nuova String
Molte delle stesse operazioni disponibili con Vec<T>
sono disponibili anche con String
poiché String
è effettivamente implementata come un wrapper intorno a un vettore di byte con alcune garanzie, restrizioni e capacità extra. Un esempio di una funzione che funziona allo stesso modo con Vec<T>
e String
è la funzione new
per creare un'istanza, mostrata nel Listing 8-11.
fn main() { let mut s = String::new(); }
Questa linea crea una nuova stringa vuota chiamata s
, nella quale possiamo poi caricare i dati. Spesso, avremo alcuni dati iniziali con cui vogliamo iniziare la stringa. Per questo, usiamo il metodo to_string
, che è disponibile su qualsiasi tipo che implementa il trait Display
, come fanno i letterali di stringa. Listing 8-12 mostra due esempi.
fn main() { let data = "initial contents"; let s = data.to_string(); // the method also works on a literal directly: let s = "initial contents".to_string(); }
Questo codice crea una stringa contenente initial contents
.
Possiamo anche utilizzare la funzione String::from
per creare una String
da un letterale di stringa. Il codice nel Listing 8-13 è equivalente al codice nel Listing 8-12 che utilizza to_string
.
fn main() { let s = String::from("initial contents"); }
Poiché le stringhe sono utilizzate per molte cose, possiamo utilizzare molte API generiche diverse per le stringhe, fornendoci molte opzioni. Alcune di esse possono sembrare ridondanti, ma tutte hanno il loro posto! In questo caso, String::from
e to_string
fanno la stessa cosa, quindi quale scegliete è una questione di stile e leggibilità.
Ricorda che le stringhe sono codificate UTF-8, quindi possiamo includere in esse qualsiasi dato codificato correttamente, come mostrato nel Listing 8-14.
fn main() { let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); }
Tutti questi sono valori di String
validi.
Aggiornare una String
Una String
può crescere di dimensione e i suoi contenuti possono cambiare, proprio come i contenuti di un Vec<T>
, se vi si aggiungono più dati. Inoltre, è possibile usare comodamente l'operatore +
o la macro format!
per concatenare valori String
.
Appendere a una String con push_str
e push
Possiamo far crescere una String
utilizzando il metodo push_str
per aggiungere una string slice, come mostrato nel Listing 8-15.
fn main() { let mut s = String::from("foo"); s.push_str("bar"); }
Dopo queste due linee, s
conterrà foobar
. Il metodo push_str
prende una string slice perché non necessariamente vogliamo prendere possesso del parametro. Per esempio, nel codice nel Listing 8-16, vogliamo poter utilizzare s2
dopo aver aggiunto i suoi contenuti a s1
.
fn main() { let mut s1 = String::from("foo"); let s2 = "bar"; s1.push_str(s2); println!("s2 is {s2}"); }
Se il metodo push_str
prendesse possesso di s2
, non potremmo stampare il suo valore nell'ultima riga. Tuttavia, questo codice funziona come ci aspettiamo!
Il metodo push
prende un singolo carattere come parametro e lo aggiunge alla String
. Il Listing 8-17 aggiunge la lettera l a una String
utilizzando il metodo push
.
fn main() { let mut s = String::from("lo"); s.push('l'); }
Di conseguenza, s
conterrà lol
.
Concatenazione con l'Operatore +
o la Macro format!
Spesso, vorrai combinare due stringhe esistenti. Un modo per farlo è utilizzare l'operatore +
, come mostrato nel Listing 8-18.
fn main() { let s1 = String::from("Hello, "); let s2 = String::from("world!"); let s3 = s1 + &s2; // note s1 has been moved here and can no longer be used }
La stringa s3
conterrà Hello, world!
. Il motivo per cui s1
non è più valido dopo l'aggiunta e il motivo per cui abbiamo usato un riferimento a s2
ha a che fare con la firma del metodo che viene chiamato quando usiamo l'operatore +
. L'operatore +
utilizza il metodo add
, la cui firma è simile a questa:
fn add(self, s: &str) -> String {
Nella libreria standard, vedrai add
definito utilizzando tipi generici e tipologie associate. Qui, abbiamo sostituito i tipi concreti, che è ciò che accade quando chiamiamo questo metodo con valori String
. Discutteremo i generici nel Capitolo 10. Questa firma ci fornisce gli indizi necessari per comprendere i punti difficili dell'operatore +
.
Per prima cosa, s2
ha un &
, il che significa che stiamo aggiungendo un reference della seconda stringa alla prima stringa. Questo è dovuto al parametro s
nella funzione add
: possiamo aggiungere solo un &str
a una String
; non possiamo aggiungere due valori String
insieme. Ma aspetta—il tipo di &s2
è &String
, non &str
, come specificato nel secondo parametro per add
. Quindi perché il Listing 8-18 compila?
Il motivo per cui possiamo utilizzare &s2
nella chiamata a add
è che il compilatore può coercere l'argomento &String
in un &str
. Quando chiamiamo il metodo add
, Rust utilizza una dereference coercion, che qui trasforma &s2
in &s2[..]
. Discutteremo la dereference coercion più in dettaglio nel Capitolo 15. Poiché add
non prende possesso del parametro s
, s2
sarà ancora una String
valida dopo questa operazione.
In secondo luogo, possiamo vedere nella firma che add
prende possesso di self
perché self
non ha un &
. Questo significa che s1
nel Listing 8-18 sarà spostato nella chiamata a add
e non sarà più valido dopo. Quindi, sebbene let s3 = s1 + &s2;
sembri che copierà entrambe le stringhe e ne creerà una nuova, questa istruzione in realtà prende possesso di s1
, appende una copia dei contenuti di s2
, e poi restituisce proprietà del risultato. In altre parole, sembra che stia facendo molte copie, ma non lo fa; l'implementazione è più efficiente della copia.
Se abbiamo bisogno di concatenare più stringhe, il comportamento dell'operatore +
diventa insostenibile:
fn main() { let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); let s = s1 + "-" + &s2 + "-" + &s3; }
A questo punto, s
sarà tic-tac-toe
. Con tutti i caratteri +
e "
, è difficile vedere cosa stia succedendo. Per combinare le stringhe in modi più complicati, possiamo invece utilizzare la macro format!
:
fn main() { let s1 = String::from("tic"); let s2 = String::from("tac"); let s3 = String::from("toe"); let s = format!("{s1}-{s2}-{s3}"); }
Questo codice imposta anche s
a tic-tac-toe
. La macro format!
funziona come println!
, ma invece di stampare l'output sullo schermo, restituisce una String
con il contenuto. La versione del codice che utilizza format!
è molto più facile da leggere, e il codice generato dalla macro format!
utilizza riferimenti in modo che questa chiamata non prenda possesso di nessuno dei suoi parametri.
Indicizzare nelle Stringhe
In molti altri linguaggi di programmazione, accedere ai singoli caratteri in una stringa facendo riferimento ad essi per indice è un'operazione valida e comune. Tuttavia, se provi ad accedere a parti di una String
utilizzando la sintassi di indicizzazione in Rust, otterrai un errore. Considera il codice non valido nel Listing 8-19.
fn main() {
let s1 = String::from("hello");
let h = s1[0];
}
Questo codice risulterà nel seguente errore:
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
error[E0277]: the type `String` cannot be indexed by `{integer}`
--> src/main.rs:3:13
|
3 | let h = s1[0];
| ^^^^^ `String` cannot be indexed by `{integer}`
|
= help: the trait `Index<{integer}>` is not implemented for `String`
= help: the following other types implement trait `Index<Idx>`:
<String as Index<RangeFrom<usize>>>
<String as Index<RangeFull>>
<String as Index<RangeInclusive<usize>>>
<String as Index<RangeTo<usize>>>
<String as Index<RangeToInclusive<usize>>>
<String as Index<std::ops::Range<usize>>>
For more information about this error, try `rustc --explain E0277`.
error: could not compile `collections` due to previous error
L'errore e la nota raccontano la storia: le stringhe Rust non supportano l'indicizzazione. Ma perché no? Per rispondere a questa domanda, dobbiamo discutere su come Rust memorizza le stringhe in memoria.
Rappresentazione Interna
Una String
è un wrapper su un Vec<u8>
. Diamo un'occhiata ad alcune delle nostre stringhe esemplari codificate UTF-8 dal Listing 8-14. In primo luogo, questo:
fn main() { let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); }
In questo caso, len
sarà 4
, il che significa che il vettore che memorizza la stringa Hola
è lungo 4 byte. Ognuna di queste lettere prende un byte quando viene codificata in UTF-8. La seguente riga, tuttavia, può sorprenderti (nota che questa stringa inizia con la lettera maiuscola cirillica Ze, non il numero 3):
fn main() { let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); let hello = String::from("Hello"); let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); }
Se ti venisse chiesto quanto è lunga la stringa, potresti dire 12. In realtà, la risposta di Rust è 24: questo è il numero di byte che ci vogliono per codificare “Здравствуйте” in UTF-8, poiché ciascun valore scalare Unicode in quella stringa prende 2 byte di memoria. Pertanto, un indice nei byte della stringa non sempre corrisponderà a un valore scalare Unicode valido. Per dimostrare, considera questo codice Rust non valido:
let hello = "Здравствуйте";
let answer = &hello[0];
Sai già che answer
non sarà З
, la prima lettera. Quando codificata in UTF-8, il primo byte di З
è 208
e il secondo è 151
, quindi sembrerebbe che answer
dovrebbe effettivamente essere 208
, ma 208
non è un carattere valido da solo. Restituire 208
probabilmente non è ciò che un utente vorrebbe se chiedesse la prima lettera di questa stringa; tuttavia, quello è l'unico dato che Rust ha a byte index 0. Gli utenti generalmente non vogliono che il valore del byte venga restituito, anche se la stringa contiene solo lettere latine: se &"hello"[0]
fosse codice valido che restituiva il valore del byte, restituirebbe 104
, non h
.
La risposta è, quindi, che per evitare di restituire un valore inatteso e causare bug che potrebbero non essere scoperti immediatamente, Rust non compila affatto questo codice e impedisce incomprensioni fin dall'inizio del processo di sviluppo.
Bytes, Valori Scalari e Cluster di Grafemi! Ahimè!
Un altro punto su UTF-8 è che ci sono effettivamente tre modi rilevanti per guardare le stringhe dal punto di vista di Rust: come byte, valori scalari e cluster di grafemi (la cosa più simile a ciò che chiameremmo lettere).
Se guardiamo la parola hindi “नमस्ते” scritta nell'alfabeto devanagari, è memorizzata come un vettore di valori u8
che sembra così:
[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
224, 165, 135]
Sono 18 byte ed è come i computer memorizzano alla fine questi dati. Se li guardiamo come valori scalari Unicode, che è ciò che il tipo char
di Rust è, quei byte sembrano così:
['न', 'म', 'स', '्', 'त', 'े']
Ci sono sei valori char
qui, ma il quarto e il sesto non sono lettere: sono diacritici che non hanno senso da soli. Infine, se li guardiamo come cluster di grafemi, otterremmo ciò che una persona chiamerebbe le quattro lettere che compongono la parola hindi:
["न", "म", "स्", "ते"]
Rust fornisce diversi modi di interpretare i dati grezzi della stringa che i computer memorizzano in modo che ogni programma possa scegliere l'interpretazione di cui ha bisogno, indipendentemente dalla lingua umana in cui i dati sono.
Un ultimo motivo per cui Rust non ci permette di indicizzare una String
per ottenere un carattere è che le operazioni di indicizzazione sono generalmente considerate operazioni a tempo costante (O(1)). Ma non è possibile garantire quella prestazione con una String
, perché Rust dovrebbe camminare attraverso i contenuti dall'inizio all'indice per determinare quanti caratteri validi ci sono.
Slicing delle Stringhe
Indicizzare una stringa è spesso un'idea cattiva perché non è chiaro quale dovrebbe essere il tipo di ritorno dell'operazione di indicizzazione della stringa: un valore di byte, un carattere, un cluster di grafemi o una string slice. Se davvero hai bisogno di usare indici per creare string slice, quindi, Rust ti chiede di essere più specifico.
Piuttosto che indicizzare usando []
con un singolo numero, puoi utilizzare []
con un range per creare una string slice contenente particolari byte:
#![allow(unused)] fn main() { let hello = "Здравствуйте"; let s = &hello[0..4]; }
Qui, s
sarà una &str
che contiene i primi quattro byte della stringa. In precedenza, abbiamo menzionato che ciascuno di questi caratteri era due byte, il che significa che s
sarà Зд
.
Se provassimo a fare uno slice di solo una parte dei byte di un carattere con qualcosa come &hello[0..1]
, Rust andrebbe in panic a runtime nello stesso modo in cui accadrebbe se si accedesse a un indice non valido in un vettore:
$ cargo run
Compiling collections v0.1.0 (file:///projects/collections)
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/collections`
thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside 'З' (bytes 0..2) of `Здравствуйте`', src/main.rs:4:14
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Dovresti fare attenzione quando crei slice di stringhe con intervalli, perché farlo può far crashare il tuo programma.
Metodi per Iterare sulle Stringhe
Il miglior modo per operare su pezzi di stringhe è essere espliciti riguardo a se vuoi caratteri o byte. Per i singoli valori scalari Unicode, usa il metodo chars
. Chiamare chars
su “Зд” separa e restituisce due valori di tipo char
, e puoi iterare sul risultato per accedere a ciascun elemento:
#![allow(unused)] fn main() { for c in "Зд".chars() { println!("{c}"); } }
Questo codice stamperà quanto segue:
З
д
In alternativa, il metodo bytes
restituisce ogni byte grezzo, il che potrebbe essere appropriato per il tuo dominio:
#![allow(unused)] fn main() { for b in "Зд".bytes() { println!("{b}"); } }
Questo codice stamperà i quattro byte che compongono questa stringa:
208
151
208
180
Ma assicurati di ricordare che i valori scalari Unicode validi possono essere composti da più di un byte.
Recuperare le cluster dei grafemi dalle stringhe, come accade con la scrittura Devanagari, è complesso, quindi questa funzionalità non è fornita dalla libreria standard. I Crates sono disponibili su crates.io se questa è la funzionalità di cui hai bisogno.
Le Stringhe non sono così Semplici
Per riassumere, le stringhe sono complicate. I diversi linguaggi di programmazione fanno scelte diverse riguardo a come presentare questa complessità al programmatore. Rust ha scelto di rendere la gestione corretta dei dati String
il comportamento predefinito per tutti i programmi Rust, il che significa che i programmatori devono pensare di più alla gestione dei dati UTF-8 sin dall'inizio. Questo compromesso espone più della complessità delle stringhe rispetto a quanto apparente in altri linguaggi di programmazione, ma ti previene dall'avere a che fare con errori relativi a caratteri non ASCII più avanti nel ciclo di sviluppo.
La buona notizia è che la libreria standard offre molte funzionalità costruite sui tipi String
e &str
per aiutare a gestire correttamente queste situazioni complesse. Assicurati di controllare la documentazione per metodi utili come contains
per cercare in una stringa e replace
per sostituire parti di una stringa con un'altra stringa.
Passiamo a qualcosa di un po' meno complesso: gli hash map!
Memorizzare Chiavi con Valori Associati in Hash Map
L'ultima delle nostre collezioni comuni è l'hash map. Il tipo HashMap<K, V>
memorizza una mappatura di chiavi di tipo K
con valori di tipo V
utilizzando una funzione di hashing,
che determina come collocare queste chiavi e valori in memoria.
Molti linguaggi di programmazione supportano questo tipo di struttura dati, ma spesso utilizzano un nome diverso, come hash, map, object, hash table, dictionary o array associativo, solo per citarne alcuni.
Le hash map sono utili quando si desidera cercare i dati non utilizzando un indice, come si fa con i vettori, ma utilizzando una chiave che può essere di qualsiasi tipo. Ad esempio, in un gioco, si potrebbe tenere traccia del punteggio di ogni squadra in una hash map in cui ogni chiave è il nome di una squadra e i valori sono i punteggi di ogni squadra. Dato un nome di squadra, si può recuperare il suo punteggio.
In questa sezione esamineremo l'API di base delle hash map, ma molte altre funzionalità sono nascoste nelle funzioni definite su HashMap<K, V>
dalla libreria standard. Come sempre, consultare la documentazione della libreria standard per ulteriori informazioni.
Creare una Nuova Hash Map
Un modo per creare una hash map vuota è utilizzare new
e aggiungere elementi con insert
. Nel Listato 8-20, stiamo tenendo traccia dei punteggi di due squadre i cui nomi sono Blue e Yellow. La squadra Blue inizia con 10 punti e la squadra Yellow inizia con 50 punti.
fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); }
Nota che dobbiamo prima use
HashMap
dalla parte delle collezioni della libreria standard. Delle nostre tre collezioni comuni, questa è la meno utilizzata, quindi non è inclusa nelle funzionalità portate automaticamente nel scope nel prelude. Anche le hash map hanno meno supporto dalla libreria standard; ad esempio, non c'è una macro incorporata per costruirle.
Come i vettori, le hash map memorizzano i loro dati nell'heap. Questa HashMap
ha chiavi di tipo String
e valori di tipo i32
. Come i vettori, anche le hash map sono omogenee: tutte le chiavi devono avere lo stesso tipo e tutti i valori devono avere lo stesso tipo.
Accesso ai Valori in una Hash Map
Possiamo ottenere un valore dalla hash map fornendo la sua chiave al metodo get
, come mostrato nel Listato 8-21.
fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); let team_name = String::from("Blue"); let score = scores.get(&team_name).copied().unwrap_or(0); }
Qui, score
avrà il valore associato alla squadra Blue, e il risultato sarà 10
. Il metodo get
restituisce un Option<&V>
; se non c'è valore per quella chiave nella hash map, get
restituirà None
. Questo programma gestisce l'Option
chiamando copied
per ottenere un Option<i32>
anziché un Option<&i32>
, quindi unwrap_or
per impostare score
a zero se scores
non ha una voce per la chiave.
Possiamo iterare su ogni coppia chiave-valore in una hash map in modo simile a come facciamo con i vettori, usando un for
loop:
fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Yellow"), 50); for (key, value) in &scores { println!("{key}: {value}"); } }
Questo codice stamperà ogni coppia in un ordine arbitrario:
Yellow: 50
Blue: 10
Hash Map e Ownership
Per i tipi che implementano il Copy
trait, come i32
, i valori vengono copiati nella hash map. Per i valori posseduti come String
, i valori verranno spostati e la hash map diventerà il proprietario di questi valori, come dimostrato nel Listato 8-22.
fn main() { use std::collections::HashMap; let field_name = String::from("Favorite color"); let field_value = String::from("Blue"); let mut map = HashMap::new(); map.insert(field_name, field_value); // field_name and field_value are invalid at this point, try using them and // see what compiler error you get! }
Non siamo in grado di usare le variabili field_name
e field_value
dopo che sono state spostate nella hash map con la chiamata a insert
.
Se inseriamo riferimenti a valori nella hash map, i valori non verranno spostati nella hash map. I valori ai quali i riferimenti puntano devono essere validi per almeno tutto il tempo in cui la hash map è valida. Parleremo più di queste problematiche nella sezione “Validating References with Lifetimes” nel Capitolo 10.
Aggiornare una Hash Map
Sebbene il numero di coppie chiave-valore sia espandibile, ogni chiave unica può avere solo un valore associato alla volta (ma non viceversa: ad esempio, sia la squadra Blue che la squadra Yellow potrebbero avere il valore 10
memorizzato nella hash map scores
).
Quando si desidera modificare i dati in una hash map, è necessario decidere come gestire il caso in cui una chiave ha già un valore assegnato. Si potrebbe sostituire il vecchio valore con il nuovo valore, ignorando completamente il vecchio valore. Si potrebbe mantenere il vecchio valore e ignorare il nuovo valore, aggiungendo il nuovo valore solo se la chiave non ha già un valore. Oppure si potrebbe combinare il vecchio valore e il nuovo valore. Vediamo come fare ognuna di queste cose!
Sovrascrivere un Valore
Se inseriamo una chiave e un valore in una hash map e poi inseriamo quella stessa chiave con un valore diverso, il valore associato a quella chiave verrà sostituito. Anche se il codice nel Listato 8-23 chiama insert
due volte, la hash map conterrà solo una coppia chiave-valore perché stiamo inserendo il valore per la chiave della squadra Blue entrambe le volte.
fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.insert(String::from("Blue"), 25); println!("{:?}", scores); }
Questo codice stamperà {"Blue": 25}
. Il valore originale di 10
è stato sovrascritto.
Aggiungere una Chiave e un Valore Solo Se una Chiave Non è Presente
È comune verificare se una particolare chiave esiste già nella hash map con un valore e quindi intraprendere le seguenti azioni: se la chiave esiste nella hash map, il valore esistente deve rimanere com'è; se la chiave non esiste, inserirla con un valore.
Le hash map hanno un'API speciale per questo chiamata entry
che prende la chiave che si desidera verificare come parametro. Il valore restituito del metodo entry
è un enum chiamato Entry
che rappresenta un valore che potrebbe o non potrebbe esistere. Diciamo che vogliamo verificare se la chiave per la squadra Yellow ha un valore associato. Se non lo ha, vogliamo inserire il valore 50
, e lo stesso per la squadra Blue. Utilizzando l'API entry
, il codice appare come nel Listato 8-24.
fn main() { use std::collections::HashMap; let mut scores = HashMap::new(); scores.insert(String::from("Blue"), 10); scores.entry(String::from("Yellow")).or_insert(50); scores.entry(String::from("Blue")).or_insert(50); println!("{:?}", scores); }
Il metodo or_insert
su Entry
è definito per restituire un riferimento mutabile al valore per la chiave Entry
corrispondente se quella chiave esiste, e se non esiste, inserisce il parametro come nuovo valore per questa chiave e restituisce un riferimento mutabile al nuovo valore. Questa tecnica è molto più pulita che scrivere la logica da soli e, inoltre, si combina meglio con il borrow checker.
Eseguendo il codice nel Listato 8-24 verrà stampato {"Yellow": 50, "Blue": 10}
. La prima chiamata a entry
inserirà la chiave per la squadra Yellow con il valore 50
perché la squadra Yellow non ha già un valore. La seconda chiamata a entry
non cambierà la hash map perché la squadra Blue ha già il valore 10
.
Aggiornare un Valore Basato sul Vecchio Valore
Un altro caso d'uso comune per le hash map è cercare il valore di una chiave e poi aggiornarlo basato sul vecchio valore. Ad esempio, il Listato 8-25 mostra il codice che conta quante volte ogni parola appare in un testo. Utilizziamo una hash map con le parole come chiavi e incrementiamo il valore per tenere traccia di quante volte abbiamo visto quella parola. Se è la prima volta che vediamo una parola, inseriremo il valore 0
.
fn main() { use std::collections::HashMap; let text = "hello world wonderful world"; let mut map = HashMap::new(); for word in text.split_whitespace() { let count = map.entry(word).or_insert(0); *count += 1; } println!("{:?}", map); }
Questo codice stamperà {"world": 2, "hello": 1, "wonderful": 1}
. Si potrebbe vedere la stessa coppia chiave-valore in un ordine diverso: ricordate dalla sezione “Accesso ai Valori in una Hash Map” che iterare su una hash map avviene in un ordine arbitrario.
Il metodo split_whitespace
restituisce un iteratore su sub-slice, separati da spazi bianchi, del valore in text
. Il metodo or_insert
restituisce un riferimento mutabile (&mut V
) al valore per la chiave specificata. Qui, memorizziamo tale riferimento mutabile nella variabile count
, quindi per assegnare a quel valore, dobbiamo prima dereferenziare count
utilizzando l'asterisco (*
). Il riferimento mutabile esce dallo scope alla fine del ciclo for
, quindi tutti questi cambiamenti sono sicuri e consentiti dalle regole di borrowing.
Funzioni di Hashing
Per impostazione predefinita, HashMap
utilizza una funzione di hashing chiamata SipHash che può offrire resistenza agli attacchi di denial-of-service (DoS) che coinvolgono le hash table1. Questo non è l'algoritmo di hashing più veloce disponibile, ma il compromesso per una migliore sicurezza che viene con la riduzione delle prestazioni vale la pena. Se si profila il proprio codice e si scopre che la funzione di hash predefinita è troppo lenta per i propri scopi, è possibile passare a un'altra funzione specificando un altro hasher. Un hasher è un tipo che implementa il trait BuildHasher
. Parleremo di trait e come implementarli nel Capitolo 10. Non è necessariamente necessario implementare il proprio hasher da zero; crates.io ha librerie condivise da altri utenti di Rust che forniscono hashers per implementare molti algoritmi di hashing comuni.
Riepilogo
I vettori, le stringhe e le hash map forniranno una grande quantità di funzionalità necessarie nei programmi quando è necessario memorizzare, accedere e modificare i dati. Ecco alcuni esercizi che dovresti ora essere in grado di risolvere:
- Data una lista di interi, usa un vettore e restituisci la mediana (quando ordinata, il valore nella posizione centrale) e la moda (il valore che si verifica più frequentemente; una hash map sarà utile qui) della lista.
- Converti le stringhe in pig latin. La prima consonante di ogni parola viene spostata alla fine della parola e viene aggiunto ay, quindi first diventa irst-fay. Le parole che iniziano con una vocale hanno hay aggiunto alla fine (apple diventa apple-hay). Tieni presente i dettagli sulla codifica UTF-8!
- Utilizzando una hash map e vettori, crea un'interfaccia testuale per consentire a un utente di aggiungere nomi di dipendenti a un dipartimento in un'azienda; ad esempio, “Aggiungi Sally all'Ingegneria” o “Aggiungi Amir alle Vendite”. Quindi consenti all'utente di recuperare un elenco di tutte le persone in un dipartimento o tutte le persone nell'azienda per dipartimento, ordinate alfabeticamente.
La documentazione dell'API della libreria standard descrive i metodi che i vettori, le stringhe e le hash map hanno che saranno utili per questi esercizi!
Stiamo entrando in programmi più complessi in cui le operazioni possono fallire, quindi è il momento perfetto per discutere la gestione degli errori. Ne parleremo prossimamente!
Gestione degli Errori
Gli errori sono un dato di fatto nel software, quindi Rust ha una serie di funzionalità per gestire situazioni in cui qualcosa va storto. In molti casi, Rust richiede di riconoscere la possibilità di un errore e di intraprendere qualche azione prima che il tuo codice venga compilato. Questo requisito rende il tuo programma più robusto assicurando che scoprirai gli errori e li gestirai appropriatamente prima di distribuire il tuo codice in produzione!
Rust raggruppa gli errori in due categorie principali: errori recuperabili e non recuperabili. Per un errore recuperabile, come un errore di file non trovato, molto probabilmente vogliamo solo segnalare il problema all'utente e riprovare l'operazione. Gli errori non recuperabili sono sempre sintomi di bug, come tentare di accedere a una posizione oltre la fine di un array, e quindi vogliamo fermare immediatamente il programma.
La maggior parte dei linguaggi non distingue tra questi due tipi di errori e li gestisce entrambi allo stesso modo, utilizzando meccanismi come le eccezioni. Rust non ha eccezioni. Invece, ha il tipo Result<T, E>
per errori recuperabili e la macro panic!
che interrompe l'esecuzione quando il programma incontra un errore non recuperabile. Questo capitolo copre prima la chiamata a panic!
e poi parla di restituire valori Result<T, E>
. Inoltre, esploreremo considerazioni quando si decide se tentare di recuperare da un errore o fermare l'esecuzione.
Errori irreversibili con panic!
A volte succedono cose brutte nel tuo codice, e non c'è nulla che tu possa fare a riguardo. In questi casi, Rust ha la macro panic!
. Ci sono due modi per causare un panic in pratica: compiendo un'azione che causa il panic del nostro codice (come accedere a un array oltre la fine) o chiamando esplicitamente la macro panic!
. In entrambi i casi, causiamo un panic nel nostro programma. Per impostazione predefinita, questi panic stamperanno un messaggio di errore, faranno il unwind, puliranno lo stack e poi termineranno. Tramite una variabile d'ambiente, puoi anche far visualizzare a Rust lo stack delle chiamate quando si verifica un panic per rendere più facile rintracciare la fonte del panic.
Fare Unwind dello Stack o Abortire in risposta a un Panic
Per impostazione predefinita, quando si verifica un panic, il programma inizia a fare unwinding, il che significa che Rust risale lo stack e pulisce i dati di ciascuna funzione che incontra. Tuttavia, risalire e pulire è un lavoro intenso. Pertanto, Rust ti consente di scegliere l'alternativa di abortire immediatamente, che termina il programma senza pulire.
La memoria utilizzata dal programma dovrà quindi essere pulita dal sistema operativo. Se nel tuo progetto hai bisogno di ridurre il più possibile la dimensione del binario risultante, puoi passare dall'unwinding all'aborting su un panic aggiungendo
panic = 'abort'
alle sezioni appropriate[profile]
nel tuo file Cargo.toml. Ad esempio, se vuoi abortire su panic in modalità release, aggiungi questo:[profile.release] panic = 'abort'
Proviamo a chiamare panic!
in un programma semplice:
Nome del file: src/main.rs
fn main() { panic!("crash and burn"); }
Quando esegui il programma, vedrai qualcosa di simile a questo:
$ cargo run
Compiling panic v0.1.0 (file:///projects/panic)
Finished dev [unoptimized + debuginfo] target(s) in 0.25s
Running `target/debug/panic`
thread 'main' panicked at 'crash and burn', src/main.rs:2:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
La chiamata a panic!
causa il messaggio di errore contenuto nelle ultime due righe. La prima riga mostra il nostro messaggio di panic e il punto nel nostro codice sorgente dove si è verificato il panic: src/main.rs:2:5 indica che è la seconda riga, quinto carattere del nostro file src/main.rs.
In questo caso, la riga indicata fa parte del nostro codice, e se andiamo a quella riga, vediamo la chiamata alla macro panic!
. In altri casi, la chiamata a panic!
potrebbe essere nel codice che il nostro codice chiama, e il nome del file e il numero della riga riportati dal messaggio di errore saranno il codice di qualcun altro dove è stata chiamata la macro panic!
, non la riga del nostro codice che ha portato infine alla chiamata a panic!
.
Possiamo utilizzare il backtrace delle funzioni da cui è stata fatta la chiamata a panic!
per capire la parte del nostro codice che sta causando il problema. Per capire come usare un backtrace di panic!
, vediamo un altro esempio e capiamo come appare quando una chiamata a panic!
proviene da una libreria a causa di un bug nel nostro codice anziché dal nostro codice che chiama direttamente la macro. Il Listing 9-1 ha del codice che tenta di accedere a un indice in un vettore oltre il range degli indici validi.
Nome del file: src/main.rs
fn main() { let v = vec![1, 2, 3]; v[99]; }
Qui stiamo tentando di accedere al 100° elemento del nostro vettore (che è all'indice 99 perché l'indicizzazione inizia da zero), ma il vettore ha solo tre elementi. In questa situazione, Rust farà panic. Utilizzare []
dovrebbe restituire un elemento, ma se passi un indice non valido, non c'è nessun elemento che Rust potrebbe restituire correttamente.
In C, tentare di leggere oltre la fine di una struttura dati è un comportamento indefinito. Potresti ottenere ciò che si trova nella posizione di memoria che corrisponderebbe a quell'elemento nella struttura dati, anche se la memoria non appartiene a quella struttura. Questo è chiamato buffer overread e può portare a vulnerabilità di sicurezza se un attaccante è in grado di manipolare l'indice in modo da leggere dati a cui non dovrebbe essere consentito di accedere memorizzati dopo la struttura dati.
Per proteggere il tuo programma da questo tipo di vulnerabilità, se tenti di leggere un elemento a un indice che non esiste, Rust fermerà l'esecuzione e rifiuterà di continuare. Proviamolo e vediamo:
$ cargo run
Compiling panic v0.1.0 (file:///projects/panic)
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/panic`
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Questo errore punta alla riga 4 del nostro main.rs dove tentiamo di accedere all'indice 99
del vettore in v
.
La riga note:
ci dice che possiamo impostare la variabile d'ambiente RUST_BACKTRACE
per ottenere un backtrace di esattamente ciò che è successo per causare l'errore. Un backtrace è un elenco di tutte le funzioni che sono state chiamate fino a questo punto. I backtrace in Rust funzionano come in altri linguaggi: la chiave per leggere il backtrace è iniziare dall'alto e leggere fino a vedere i file che hai scritto tu. Quello è il punto in cui è nato il problema. Le righe sopra quel punto sono codice che il tuo codice ha chiamato; le righe sotto sono codice che ha chiamato il tuo codice. Queste righe prima e dopo possono includere codice core di Rust, codice della libreria standard o crates che stai usando. Proviamo a ottenere un backtrace impostando la variabile d'ambiente RUST_BACKTRACE
a qualsiasi valore eccetto 0
. Il Listing 9-2 mostra un output simile a quello che vedrai.
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99
stack backtrace:
0: rust_begin_unwind
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/std/src/panicking.rs:645:5
1: core::panicking::panic_fmt
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/panicking.rs:72:14
2: core::panicking::panic_bounds_check
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/panicking.rs:208:5
3: <usize as core::slice::index::SliceIndex<[T]>>::index
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/slice/index.rs:255:10
4: core::slice::index::<impl core::ops::index::Index<I> per [T]>::index
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/slice/index.rs:18:9
5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/alloc/src/vec/mod.rs:2770:9
6: panic::main
at ./src/main.rs:4:6
7: core::ops::function::FnOnce::call_once
at /rustc/07dca489ac2d933c78d3c5158e3f43beefeb02ce/library/core/src/ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
È un sacco di output! L'output esatto che vedrai potrebbe essere diverso a seconda del sistema operativo e della versione di Rust. Per ottenere backtrace con queste informazioni, devono essere abilitati i simboli di debug. I simboli di debug sono abilitati per impostazione predefinita utilizzando cargo build
o cargo run
senza il flag --release
, come abbiamo fatto qui.
Nell'output nel Listing 9-2, la riga 6 del backtrace punta alla riga nel nostro progetto che sta causando il problema: la riga 4 di src/main.rs. Se non vogliamo che il nostro programma faccia panic, dovremmo iniziare la nostra indagine dal punto indicato dalla prima riga che menziona un file che abbiamo scritto noi. Nel Listing 9-1, dove abbiamo deliberatamente scritto codice che farebbe panic, il modo per risolvere il panic è non richiedere un elemento oltre il range degli indici del vettore. Quando il tuo codice farà panic in futuro, dovrai capire quale azione il codice sta intraprendendo con quali valori per causare il panic e cosa dovrebbe fare il codice invece.
Torneremo su panic!
e quando dovremmo e non dovremmo usare panic!
per gestire le condizioni di errore nella sezione “To panic!
or Not to panic!
” più avanti in questo capitolo. Prossimamente, vedremo come recuperare da un errore usando Result
.
Errori Recuperabili con Result
La maggior parte degli errori non sono così gravi da richiedere l'arresto completo del programma. A volte, quando una funzione fallisce è per una ragione che puoi facilmente interpretare e a cui puoi rispondere. Ad esempio, se provi ad aprire un file e quell'operazione fallisce perché il file non esiste, potresti voler creare il file invece di terminare il processo.
Ricorda da “Gestione del Potenziale Fallimento con Result
” nel Capitolo 2 che l'enum Result
è definito come avente due varianti, Ok
e Err
, come segue:
#![allow(unused)] fn main() { enum Result<T, E> { Ok(T), Err(E), } }
I T
e E
sono parametri di tipi generici: discuteremo i generici più in dettaglio nel Capitolo 10. Quello che devi sapere ora è che T
rappresenta il tipo del valore che verrà restituito in caso di successo all'interno della variante Ok
, e E
rappresenta il tipo dell'errore che verrà restituito in caso di fallimento all'interno della variante Err
. Poiché Result
ha questi parametri di tipo generico, possiamo usare il tipo Result
e le funzioni definite su di esso in molte situazioni diverse in cui i valori di successo e di errore che vogliamo restituire possono differire.
Chiamiamo una funzione che restituisce un valore Result
perché la funzione potrebbe fallire. Nel Listing 9-3 proviamo ad aprire un file.
Nome File: src/main.rs
use std::fs::File; fn main() { let greeting_file_result = File::open("hello.txt"); }
Il tipo di ritorno di File::open
è un Result<T, E>
. Il parametro generico T
è stato riempito dall'implementazione di File::open
con il tipo del valore di successo, std::fs::File
, che è un handle del file. Il tipo di E
utilizzato nel valore di errore è std::io::Error
. Questo tipo di ritorno significa che la chiamata a File::open
potrebbe avere successo e restituire un handle del file da cui possiamo leggere o scrivere. La chiamata alla funzione potrebbe anche fallire: ad esempio, il file potrebbe non esistere, o potremmo non avere i permessi per accedere al file. La funzione File::open
ha bisogno di un modo per dirci se ha avuto successo o fallito e, contemporaneamente, darci l'handle del file o le informazioni sull'errore. Questa informazione è esattamente ciò che l'enum Result
trasmette.
Nel caso in cui File::open
abbia successo, il valore nella variabile greeting_file_result
sarà un'istanza di Ok
che contiene un handle del file. Nel caso in cui fallisca, il valore in greeting_file_result
sarà un'istanza di Err
che contiene più informazioni sul tipo di errore che si è verificato.
Dobbiamo aggiungere al codice nel Listing 9-3 per intraprendere azioni diverse a seconda del valore restituito da File::open
. Il Listing 9-4 mostra un modo per gestire il Result
utilizzando uno strumento di base, l'espressione match
di cui abbiamo discusso nel Capitolo 6.
Nome File: src/main.rs
use std::fs::File; fn main() { let greeting_file_result = File::open("hello.txt"); let greeting_file = match greeting_file_result { Ok(file) => file, Err(error) => panic!("Problem opening the file: {:?}", error), }; }
Nota che, come l'enum Option
, anche l'enum Result
e le sue varianti sono stati portati in ambito dal preambolo, quindi non è necessario specificare Result::
prima delle varianti Ok
e Err
nei bracci del match
.
Quando il risultato è Ok
, questo codice restituirà il valore interno file
dalla variante Ok
, e assegneremo dunque quell'handle del file alla variabile greeting_file
. Dopo il match
, possiamo usare l'handle del file per leggere o scrivere.
L'altro braccio del match
gestisce il caso in cui otteniamo un valore Err
da File::open
. In questo esempio, abbiamo scelto di chiamare la macro panic!
. Se non esiste un file chiamato hello.txt nella nostra attuale directory e eseguiamo questo codice, vedremo il seguente output dalla macro panic!
:
$ cargo run
Compiling error-handling v0.1.0 (file:///projects/error-handling)
Finished dev [unoptimized + debuginfo] target(s) in 0.73s
Running `target/debug/error-handling`
thread 'main' panicked at 'Problem opening the file: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:8:23
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Come al solito, questo output ci dice esattamente cosa è andato storto.
Gestione di Errori Diversi
Il codice nel Listing 9-4 eseguirà panic!
indipendentemente dal motivo per cui File::open
ha fallito. Tuttavia, vogliamo intraprendere azioni diverse per motivi di fallimento diversi. Se File::open
ha fallito perché il file non esiste, vogliamo creare il file e restituire l'handle al nuovo file. Se File::open
ha fallito per qualsiasi altra ragione—per esempio, perché non avevamo i permessi per aprire il file—vogliamo comunque che il codice esegua panic!
nello stesso modo in cui ha fatto nel Listing 9-4. Per questo, aggiungiamo un'espressione match
interna, mostrata nel Listing 9-5.
Nome File: src/main.rs
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let greeting_file_result = File::open("hello.txt");
let greeting_file = match greeting_file_result {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {:?}", e),
},
other_error => {
panic!("Problem opening the file: {:?}", other_error);
}
},
};
}
Il tipo del valore che File::open
restituisce all'interno della variante Err
è io::Error
, che è una struct fornita dalla libreria standard. Questa struct ha un metodo kind
che possiamo chiamare per ottenere un valore io::ErrorKind
. L'enum io::ErrorKind
è fornito dalla libreria standard e ha varianti che rappresentano i diversi tipi di errori che potrebbero derivare da un'operazione io
. La variante che vogliamo usare è ErrorKind::NotFound
, che indica che il file che stiamo tentando di aprire non esiste ancora. Quindi facciamo match
su greeting_file_result
, ma abbiamo anche un inner match su error.kind()
.
La condizione che vogliamo verificare nell'inner match è se il valore restituito da error.kind()
è la variante NotFound
dell'enum ErrorKind
. Se lo è, proviamo a creare il file con File::create
. Tuttavia, poiché anche File::create
potrebbe fallire, abbiamo bisogno di un secondo braccio nell'inner match expression. Quando il file non può essere creato, viene stampato un messaggio di errore diverso. Il secondo braccio dell'outer match rimane lo stesso, quindi il programma va in panico su qualsiasi errore diverso dall'errore di file mancante.
Alternative all'uso di
match
conResult<T, E>
Questo è un sacco di
match
! L'espressionematch
è molto utile ma anche molto primitiva. Nel Capitolo 13, imparerai riguardo ai closure, che vengono usati con molti dei metodi definiti suResult<T, E>
. Questi metodi possono essere più concisi rispetto all'uso dimatch
quando si gestiscono valoriResult<T, E>
nel tuo codice.Ad esempio, ecco un altro modo per scrivere la stessa logica mostrata nel Listing 9-5, questa volta usando closure e il metodo
unwrap_or_else
:use std::fs::File; use std::io::ErrorKind; fn main() { let greeting_file = File::open("hello.txt").unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { File::create("hello.txt").unwrap_or_else(|error| { panic!("Problem creating the file: {error:?}"); }) } else { panic!("Problem opening the file: {error:?}"); } }); }
Anche se questo codice ha lo stesso comportamento del Listing 9-5, non contiene alcuna espressione
match
ed è più pulito da leggere. Torna a questo esempio dopo aver letto il Capitolo 13 e cerca il metodounwrap_or_else
nella documentazione della libreria standard. Molti altri di questi metodi possono ripulire enormi espressionimatch
annidate quando stai gestendo errori.
Scorciatoie per il Panico su Errore: unwrap
e expect
L'uso di match
funziona abbastanza bene, ma può essere un po' prolisso e non sempre comunica bene l'intento. Il tipo Result<T, E>
ha molti metodi helper definiti su di esso per fare varie operazioni più specifiche. Il metodo unwrap
è un metodo shortcut implementato proprio come l'espressione match
che abbiamo scritto nel Listing 9-4. Se il valore Result
è la variante Ok
, unwrap
restituirà il valore all'interno dell'Ok
. Se il Result
è la variante Err
, unwrap
chiamerà la macro panic!
per noi. Ecco un esempio di unwrap
in azione:
Nome File: src/main.rs
use std::fs::File; fn main() { let greeting_file = File::open("hello.txt").unwrap(); }
Se eseguiamo questo codice senza un file hello.txt, vedremo un messaggio di errore dalla chiamata panic!
che il metodo unwrap
esegue:
thread 'main' panicked at src/main.rs:4:49:
called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }
Allo stesso modo, il metodo expect
ci permette anche di scegliere il messaggio di errore panic!
. Utilizzare expect
invece di unwrap
e fornire buoni messaggi di errore può trasmettere il tuo intento e rendere più facile rintracciare la fonte di un panico. La sintassi di expect
è simile a questa:
Nome File: src/main.rs
use std::fs::File; fn main() { let greeting_file = File::open("hello.txt") .expect("hello.txt should be included in this project"); }
Usiamo expect
nello stesso modo di unwrap
: per restituire l'handle del file o chiamare la macro panic!
. Il messaggio di errore utilizzato da expect
nella sua chiamata a panic!
sarà il parametro che passiamo a expect
, piuttosto che il messaggio predefinito di panic!
che unwrap
utilizza. Ecco come appare:
thread 'main' panicked at src/main.rs:5:10:
hello.txt dovrebbe essere incluso in questo progetto: Os { code: 2, kind: NotFound, message: "No such file or directory" }
Nel codice di qualità per la produzione, la maggior parte dei Rustacean sceglie expect
piuttosto che unwrap
e fornisce più contesto sul perché l'operazione è attesa per avere sempre successo. In questo modo, se le tue assunzioni si rivelano mai sbagliate, avrai più informazioni disponibili per eseguire il debug.
Propagazione degli Errori
Quando l'implementazione di una funzione chiama qualcosa che potrebbe fallire, invece di gestire l'errore all'interno della funzione stessa puoi restituire l'errore al codice chiamante in modo che possa decidere cosa fare. Questo è conosciuto come propagazione dell'errore e dà più controllo al codice chiamante, dove potrebbe esserci più informazione o logica che detta come l'errore dovrebbe essere gestito rispetto a quello che hai disponibile nel contesto del tuo codice.
Ad esempio, il Listing 9-6 mostra una funzione che legge un nome utente da un file. Se il file non esiste o non può essere letto, questa funzione restituirà quegli errori al codice che ha chiamato la funzione.
Nome File: src/main.rs
#![allow(unused)] fn main() { use std::fs::File; use std::io::{self, Read}; fn read_username_from_file() -> Result<String, io::Error> { let username_file_result = File::open("hello.txt"); let mut username_file = match username_file_result { Ok(file) => file, Err(e) => return Err(e), }; let mut username = String::new(); match username_file.read_to_string(&mut username) { Ok(_) => Ok(username), Err(e) => Err(e), } } }
Questa funzione può essere scritta in modo molto più breve, ma inizieremo facendo molte operazioni manualmente per esplorare la gestione degli errori; alla fine, mostreremo il modo più breve. Guardiamo prima il tipo di ritorno della funzione: Result<String, io::Error>
. Questo significa che la funzione restituisce un valore del tipo Result<T, E>
, dove il parametro generico T
è stato riempito con il tipo concreto String
e il tipo generico E
è stato riempito con il tipo concreto io::Error
.
Se questa funzione ha successo senza nessun problema, il codice che chiama questa funzione riceverà un valore Ok
che contiene una String
—il username
che questa funzione ha letto dal file. Se questa funzione riscontra problemi, il codice chiamante riceverà un valore Err
che contiene un'istanza di io::Error
che contiene maggiori informazioni sui problemi riscontrati. Abbiamo scelto io::Error
come tipo di ritorno di questa funzione perché succede che sia il tipo del valore di errore restituito da entrambe le operazioni che stiamo chiamando nel corpo di questa funzione che potrebbero fallire: la funzione File::open
e il metodo read_to_string
.
Il corpo della funzione inizia chiamando la funzione File::open
. Poi gestiamo il valore Result
con un match
simile al match
nel Listing 9-4. Se File::open
ha successo, l'handle del file nella variabile pattern file
diventa il valore nella variabile mutabile username_file
e la funzione continua. Nel caso di Err
, invece di chiamare panic!
, usiamo la parola chiave return
per ritornare anticipatamente dalla funzione completamente e passare il valore di errore da File::open
, ora nella variabile pattern e
, al codice chiamante come valore di errore di questa funzione.
Quindi, se abbiamo un handle del file in username_file
, la funzione crea poi una nuova String
nella variabile username
e chiama il metodo read_to_string
sull'handle del file in username_file
per leggere il contenuto del file in username
. Il metodo read_to_string
restituisce anche un Result
perché potrebbe fallire, anche se File::open
ha avuto successo. Quindi abbiamo bisogno di un altro match
per gestire quel Result
: se read_to_string
ha successo, allora la nostra funzione ha avuto successo, e restituiamo il nome utente dal file che ora è in username
avvolto in un Ok
. Se read_to_string
fallisce, restituiamo il valore di errore nello stesso modo in cui abbiamo restituito il valore di errore nel match
che ha gestito il valore di ritorno di File::open
. Tuttavia, non abbiamo bisogno di dire esplicitamente return
, perché questa è l'ultima espressione nella funzione.
Il codice che chiama questo codice gestirà quindi l'ottenimento di un valore Ok
che contiene un nome utente o un valore Err
che contiene un io::Error
. Sta al codice chiamante decidere cosa fare con quei valori. Se il codice chiamante ottiene un valore Err
, potrebbe chiamare panic!
e far collassare il programma, usare un nome utente di default, o cercare il nome utente da qualche altra parte che non sia un file, ad esempio. Non abbiamo abbastanza informazioni su ciò che il codice chiamante sta effettivamente tentando di fare, quindi propaghiamo tutte le informazioni di successo o di errore verso l'alto affinché siano gestite adeguatamente.
Questo pattern di propagazione degli errori è così comune in Rust che Rust fornisce l'operatore punto interrogativo ?
per renderlo più facile.
Una Scorciatoia per Propagare gli Errori: l'Operatore ?
Il Listing 9-7 mostra un'implementazione di read_username_from_file
che ha la stessa funzionalità del Listing 9-6, ma questa implementazione utilizza l'operatore ?
.
Nome File: src/main.rs
#![allow(unused)] fn main() { use std::fs::File; use std::io::{self, Read}; fn read_username_from_file() -> Result<String, io::Error> { let mut username_file = File::open("hello.txt")?; let mut username = String::new(); username_file.read_to_string(&mut username)?; Ok(username) } }
?
posto dopo un valore Result
è definito per funzionare quasi nello stesso modo
delle espressioni match
che abbiamo definito per gestire i valori Result
nel Listato
9-6. Se il valore del Result
è un Ok
, il valore all'interno dell'Ok
verrà
restituito da questa espressione e il programma continuerà. Se il valore è un Err
, il Err
verrà restituito da tutta la funzione come se avessimo
usato la parola chiave return
in modo che il valore di errore venga propagato al codice chiamante.
C'è una differenza tra ciò che l'espressione match
dal Listato 9-6 fa
e ciò che fa l'operatore ?
: i valori di errore a cui viene chiamato l'operatore ?
passano attraverso la funzione from
, definita nel trait From
nella libreria standard, che viene usata per convertire i valori da un tipo a un altro.
Quando l'operatore ?
chiama la funzione from
, il tipo di errore ricevuto è
convertito nel tipo di errore definito nel tipo di ritorno della funzione corrente. Questo è utile quando una funzione ritorna un tipo di errore per rappresentare
tutti i modi in cui una funzione potrebbe fallire, anche se parti potrebbero fallire per molti motivi diversi.
Per esempio, potremmo cambiare la funzione read_username_from_file
nel Listato
9-7 per restituire un tipo di errore personalizzato chiamato OurError
che definiamo. Se definiamo anche impl From<io::Error> for OurError
per costruire un'istanza di
OurError
da un io::Error
, allora le chiamate dell'operatore ?
nel corpo di
read_username_from_file
chiameranno from
e convertiranno i tipi di errore senza
bisogno di aggiungere altro codice alla funzione.
Nel contesto del Listato 9-7, il ?
alla fine della chiamata File::open
restituirà
il valore all'interno di un Ok
alla variabile username_file
. Se si verifica un errore, l'operatore ?
restituirà anticipatamente l'intera funzione e fornirà
qualsiasi valore Err
al codice chiamante. La stessa cosa vale per il ?
alla fine della chiamata read_to_string
.
L'operatore ?
elimina molte boilerplate e rende l'implementazione di questa funzione più semplice. Potremmo anche abbreviarlo ulteriormente concatenando
le chiamate ai metodi immediatamente dopo il ?
, come mostrato nel Listato 9-8.
Nome del file: src/main.rs
#![allow(unused)] fn main() { use std::fs::File; use std::io::{self, Read}; fn read_username_from_file() -> Result<String, io::Error> { let mut username = String::new(); File::open("hello.txt")?.read_to_string(&mut username)?; Ok(username) } }
Abbiamo spostato la creazione del nuovo String
in username
all'inizio della
funzione; quella parte non è cambiata. Invece di creare una variabile
username_file
, abbiamo concatenato la chiamata a read_to_string
direttamente
al risultato di File::open("hello.txt")?
. Abbiamo ancora un ?
alla fine della
chiamata read_to_string
, e rimanderemo ancora un valore Ok
contenente username
quando sia File::open
che read_to_string
riescono invece di restituire
errori. La funzionalità è di nuovo la stessa del Listato 9-6 e del Listato 9-7; questo è solo un modo diverso e più ergonomico di scriverlo.
Il Listato 9-9 mostra un modo per rendere questo ancora più breve utilizzando fs::read_to_string
.
Nome del file: src/main.rs
#![allow(unused)] fn main() { use std::fs; use std::io; fn read_username_from_file() -> Result<String, io::Error> { fs::read_to_string("hello.txt") } }
Leggere un file in una stringa è un'operazione piuttosto comune, quindi la libreria
standard fornisce la funzione comoda fs::read_to_string
che apre il file,
crea un nuovo String
, legge il contenuto del file, mette il contenuto
in quella String
, e la restituisce. Naturalmente, l'uso di fs::read_to_string
non ci dà la possibilità di spiegare tutta la gestione degli errori, quindi lo abbiamo fatto
nel modo più lungo prima.
Dove l'Operatore ?
Può Essere Utilizzato
L'operatore ?
può essere utilizzato solo in funzioni il cui tipo di ritorno è compatibile
con il valore su cui viene usato il ?
. Questo perché l'operatore ?
è definito
per eseguire un ritorno anticipato di un valore fuori dalla funzione, nello stesso modo
dell'espressione match
che abbiamo definito nel Listato 9-6. Nel Listato 9-6,
il match
stava usando un valore Result
, e il ramo di ritorno anticipato restituiva un
valore Err(e)
. Il tipo di ritorno della funzione deve essere un Result
così che
sia compatibile con questo return
.
Nel Listato 9-10, vediamo l'errore che otterremo se usiamo l'operatore ?
in una funzione main
con un tipo di ritorno che non è compatibile con il tipo del valore su cui usiamo ?
.
Nome del file: src/main.rs
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")?;
}
Questo codice apre un file, che potrebbe fallire. L'operatore ?
segue il valore Result
ritornato da File::open
, ma questa funzione main
ha il tipo di ritorno
()
, non Result
. Quando compiliamo questo codice, otteniamo il seguente messaggio di errore:
$ cargo run
Compiling error-handling v0.1.0 (file:///projects/error-handling)
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/main.rs:4:48
|
3 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
4 | let greeting_file = File::open("hello.txt")?;
| ^ cannot use the `?` operator in a function that returns `()`
|
= help: the trait `FromResidual<Result<Infallible, std::io::Error>>` is not implemented for `()`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `error-handling` due to previous error
Questo errore sottolinea che siamo autorizzati a usare l'operatore ?
solo in
una funzione che restituisce Result
, Option
, o un altro tipo che implementa
FromResidual
.
Per correggere l'errore, hai due scelte. Una scelta è cambiare il tipo di ritorno
della tua funzione per essere compatibile con il valore su cui stai usando l'operatore ?
finché non hai restrizioni che lo impediscono. L'altra scelta è utilizzare un match
o uno dei metodi Result<T, E>
per gestire il Result<T, E>
in qualunque modo sia appropriato.
Il messaggio di errore menzionava anche che ?
può essere utilizzato con i valori Option<T>
.
Come con l'uso di ?
su Result
, puoi usare ?
su Option
solo in una funzione che ritorna un Option
. Il comportamento dell'operatore ?
quando viene chiamato
su un Option<T>
è simile al suo comportamento quando viene chiamato su un Result<T, E>
:
se il valore è None
, il None
verrà restituito anticipatamente dalla funzione a
quel punto. Se il valore è Some
, il valore all'interno del Some
è il
valore risultante dell'espressione, e la funzione continua. Il Listato 9-11 ha
un esempio di una funzione che trova l'ultimo carattere della prima riga nel testo dato.
fn last_char_of_first_line(text: &str) -> Option<char> { text.lines().next()?.chars().last() } fn main() { assert_eq!( last_char_of_first_line("Hello, world\nHow are you today?"), Some('d') ); assert_eq!(last_char_of_first_line(""), None); assert_eq!(last_char_of_first_line("\nhi"), None); }
Questa funzione restituisce Option<char>
perché è possibile che ci sia un
carattere lì, ma è anche possibile che non ci sia. Questo codice prende la fetta di stringa text
come argomento e chiama il metodo lines
su di essa, che restituisce
un iteratore sulle righe nella stringa. Poiché questa funzione vuole esaminare la
prima riga, chiama next
sull'iteratore per ottenere il primo valore dell'iteratore.
Se text
è la stringa vuota, questa chiamata a next
restituirà None
, nel qual caso usiamo ?
per fermarci e restituire None
da
last_char_of_first_line
. Se text
non è la stringa vuota, next
restituirà un valore
Some
contenente una fetta di stringa della prima riga in text
.
Il ?
estrae la fetta di stringa e possiamo chiamare chars
su quella fetta di stringa
per ottenere un iteratore dei suoi caratteri. Siamo interessati all'ultimo carattere di questa prima riga, quindi chiamiamo last
per restituire l'ultimo elemento nell'iteratore.
Questo è un Opzione
perché è possibile che la prima riga sia la stringa vuota; ad esempio, se text
inizia con una riga vuota ma ha caratteri su
altre righe, come in "\nhi"
. Tuttavia, se c'è un ultimo carattere sulla prima
riga, verrà restituito nella variante Some
. L'operatore ?
nel mezzo ci dà un modo
conciso di esprimere questa logica, permettendoci di implementare la
funzione in una sola riga. Se non potessimo usare l'operatore ?
su Option
, dovremmo
implementare questa logica utilizzando più chiamate ai metodi o un'espressione match
.
Nota che puoi usare l'operatore ?
su un Result
in una funzione che restituisce
Result
, e puoi usare l'operatore ?
su un Option
in una funzione che restituisce Option
, ma non puoi mescolarli. L'operatore ?
non
converterà automaticamente un Result
in un Option
o viceversa; in quei casi,
puoi utilizzare metodi come il metodo ok
su Result
o il metodo ok_or
su Option
per fare la conversione esplicitamente.
Finora, tutte le funzioni main
che abbiamo usato restituiscono ()
. La funzione main
è speciale perché è il punto d'ingresso e il punto d'uscita di un programma eseguibile,
e ci sono restrizioni su quale possa essere il suo tipo di ritorno affinché il programma
funzioni come previsto.
Fortunatamente, main
può anche restituire un Result<(), E>
. Il Listato 9-12 ha il codice
del Listato 9-10, ma abbiamo cambiato il tipo di ritorno di main
in
Result<(), Box<dyn Error>>
e aggiunto un valore di ritorno Ok(())
alla fine. Questo
codice ora compilerà.
Nome del file: src/main.rs
use std::error::Error;
use std::fs::File;
fn main() -> Result<(), Box<dyn Error>> {
let greeting_file = File::open("hello.txt")?;
Ok(())
}
Il tipo Box<dyn Error>
è un oggetto trait, di cui parleremo nella sezione
“Usare oggetti trait che consentono valori di tipi diversi” nel Capitolo 17. Per ora, puoi
leggere Box<dyn Error>
come “qualsiasi tipo di errore”. Usare ?
su un valore Result
in una funzione main
con il tipo di errore Box<dyn Error>
è consentito
perché permette qualsiasi valore Err
di essere restituito anticipatamente. Anche se il corpo di questa funzione main
restituirà solo errori del tipo std::io::Error
, specificando Box<dyn Error>
, questa firma rimarrà corretta anche se nella funzione main
verrà aggiunto altro codice che restituisce altri errori.
Quando una funzione main
restituisce un Result<(), E>
, l'eseguibile si chiuderà con
un valore di 0
se main
restituisce Ok(())
e si chiuderà con un valore diverso da zero se main
restituisce un valore Err
. Gli eseguibili scritti in C restituiranno interi
quando si chiudono: i programmi che si chiudono con successo restituiscono l'intero 0
, e i programmi che si chiudono con errore restituiscono un qualche intero diverso da 0
.
Anche Rust restituisce interi dagli eseguibili per essere compatibili con questa convenzione.
La funzione main
può restituire qualsiasi tipo che implementa il trait
std::process::Termination
, che contiene
una funzione report
che restituisce un ExitCode
. Consulta la documentazione della libreria standard per ulteriori informazioni sull'implementazione del trait Termination
per i tuoi tipi.
Ora che abbiamo discusso i dettagli della chiamata panic!
o del ritorno di Result
, ritorniamo all'argomento su come decidere quale sia appropriato usare in quali
casi.
panic!
o non panic!
Allora, come decidere se chiamare panic!
o restituire Result
? Quando il codice va in panico, non c'è modo di recuperare. Potresti chiamare panic!
per qualsiasi situazione di errore, che ci sia o meno un modo possibile per recuperare, ma così stai decidendo che una situazione è irreversibile per conto del codice chiamante. Quando scegli di restituire un valore Result
, dai al codice chiamante delle opzioni. Il codice chiamante potrebbe scegliere di tentare di recuperare in un modo appropriato per la sua situazione, oppure potrebbe decidere che un valore Err
in questo caso è irrecuperabile, quindi può chiamare panic!
e trasformare il tuo errore recuperabile in uno irrecuperabile. Pertanto, restituire Result
è una buona scelta predefinita quando stai definendo una funzione che potrebbe fallire.
In situazioni come esempi, codice prototipo e test, è più appropriato scrivere codice che va in panico invece di restituire un Result
. Esploriamo il perché, poi discutiamo situazioni in cui il compilatore non può dire che il fallimento è impossibile, ma tu come essere umano puoi. Il capitolo si concluderà con alcune linee guida generali su come decidere se andare in panico nel codice delle librerie.
Esempi, Codice Prototipo e Test
Quando stai scrivendo un esempio per illustrare qualche concetto, includere anche un robusto codice di gestione degli errori può rendere l'esempio meno chiaro. Negli esempi, è inteso che una chiamata a un metodo come unwrap
che potrebbe andare in panico sia un segnaposto per il modo in cui vorresti che la tua applicazione gestisse gli errori, il che può differire a seconda di cosa sta facendo il resto del tuo codice.
Similarmente, i metodi unwrap
e expect
sono molto utili quando stai facendo prototipi, prima di essere pronto a decidere come gestire gli errori. Lasciano chiari marcatori nel tuo codice per quando sei pronto a rendere il tuo programma più robusto.
Se una chiamata al metodo fallisce in un test, vorresti che l'intero test fallisse, anche se quel metodo non è la funzionalità sotto test. Poiché panic!
è il modo in cui un test è segnato come un fallimento, chiamare unwrap
o expect
è esattamente ciò che dovrebbe accadere.
Casi in cui Hai Più Informazioni del Compilatore
Sarebbe anche appropriato chiamare unwrap
o expect
quando hai una qualche altra logica che garantisce che il Result
avrà un valore Ok
, ma la logica non è qualcosa che il compilatore capisce. Avrai comunque un valore Result
che devi gestire: qualsiasi operazione che stai chiamando ha comunque la possibilità di fallire in generale, anche se è logicamente impossibile nella tua situazione particolare. Se puoi assicurarti ispezionando manualmente il codice che non avrai mai una variante Err
, è perfettamente accettabile chiamare unwrap
ed è ancora meglio documentare il motivo per cui pensi che non avrai mai una variante Err
nel testo di expect
. Ecco un esempio:
fn main() { use std::net::IpAddr; let home: IpAddr = "127.0.0.1" .parse() .expect("Hardcoded IP address should be valid"); }
Stiamo creando un'istanza di IpAddr
analizzando una stringa hardcoded. Possiamo vedere che 127.0.0.1
è un indirizzo IP valido, quindi è accettabile usare expect
qui. Tuttavia, avere una stringa valida hardcoded non cambia il tipo di ritorno del metodo parse
: otteniamo comunque un valore Result
, e il compilatore ci farà comunque gestire il Result
come se la variante Err
fosse una possibilità perché il compilatore non è abbastanza intelligente da vedere che questa stringa è sempre un indirizzo IP valido. Se la stringa dell'indirizzo IP provenisse da un utente piuttosto che essere hardcoded nel programma e quindi avesse una possibilità di fallimento, vorremmo sicuramente gestire il Result
in modo più robusto. Menzionare l'assunzione che questo indirizzo IP sia hardcoded ci spingerà a cambiare expect
in un codice di gestione degli errori migliore se, in futuro, dovessimo ottenere l'indirizzo IP da qualche altra fonte.
Linee Guida per la Gestione degli Errori
È consigliabile far andare il codice in panico quando è possibile che il codice possa trovarsi in uno stato cattivo. In questo contesto, un cattivo stato è quando qualche assunzione, garanzia, contratto o invariante è stato infranto, come quando valori non validi, valori contraddittori o valori mancanti vengono passati al codice — più uno o più dei seguenti:
- Il cattivo stato è qualcosa che è inaspettato, contrariamente a qualcosa che probabilmente accade occasionalmente, come un utente che inserisce dati nel formato sbagliato.
- Il tuo codice dopo questo punto ha bisogno di non essere in questo stato cattivo, piuttosto che controllare il problema a ogni passo.
- Non c'è un buon modo per codificare queste informazioni nei tipi che usi. Lavoreremo attraverso un esempio di cosa intendiamo nella sezione “Encoding States and Behavior as Types” del Capitolo 17.
Se qualcuno chiama il tuo codice e passa valori che non hanno senso, è meglio restituire un errore se puoi così l'utente della libreria può decidere cosa vuole fare in quel caso. Tuttavia, nei casi in cui continuare potrebbe essere insicuro o dannoso, la scelta migliore potrebbe essere chiamare panic!
e avvisare la persona che usa la tua libreria del bug nel loro codice in modo che possa risolverlo durante lo sviluppo. Similmente, panic!
è spesso appropriato se stai chiamando codice esterno che è fuori dal tuo controllo e restituisce uno stato non valido che non hai modo di risolvere.
Tuttavia, quando il fallimento è previsto, è più appropriato restituire un Result
piuttosto che fare una chiamata panic!
. Esempi includono un parser che viene dato dati malformati o una richiesta HTTP che restituisce uno stato che indica che hai raggiunto un limite di velocità. In questi casi, restituire un Result
indica che il fallimento è una possibilità prevista che il codice chiamante deve decidere come gestire.
Quando il tuo codice esegue un'operazione che potrebbe mettere a rischio l'utente se viene chiamata utilizzando valori non validi, il tuo codice dovrebbe verificare che i valori siano validi prima e andare in panico se i valori non sono validi. Questo è principalmente per motivi di sicurezza: tentare di operare su dati non validi può esporre il tuo codice a vulnerabilità. Questo è il motivo principale per cui la libreria standard chiama panic!
se tenti un accesso alla memoria fuori dai limiti: cercare di accedere alla memoria che non appartiene alla struttura dati corrente è un problema di sicurezza comune. Le funzioni spesso hanno contratti: il loro comportamento è garantito solo se gli input soddisfano particolari requisiti. Andare in panico quando il contratto è violato ha senso perché una violazione del contratto indica sempre un bug lato chiamante, e non è un tipo di errore che vuoi che il codice chiamante debba gestire esplicitamente. In effetti, non c'è modo ragionevole per il codice chiamante di recuperare; i programmatori chiamanti devono correggere il codice. I contratti per una funzione, specialmente quando una violazione causerà un panico, dovrebbero essere spiegati nella documentazione dell'API per la funzione.
Tuttavia, avere molti controlli degli errori in tutte le tue funzioni sarebbe prolisso e fastidioso. Fortunatamente, puoi usare il sistema di tipi di Rust (e quindi il controllo dei tipi fatto dal compilatore) per fare molti dei controlli per te. Se la tua funzione ha un particolare tipo come parametro, puoi procedere con la logica del tuo codice sapendo che il compilatore ha già assicurato che hai un valore valido. Ad esempio, se hai un tipo piuttosto che un Option
, il tuo programma si aspetta di avere qualcosa piuttosto che niente. Il tuo codice quindi non deve gestire due casi per le varianti Some
e None
: avrà solo un caso per avere sicuramente un valore. Il codice che cerca di passare niente alla tua funzione non verrà nemmeno compilato, quindi la tua funzione non deve verificare quel caso a runtime. Un altro esempio è utilizzare un tipo integer senza segno come u32
, che assicura che il parametro non sia mai negativo.
Creazione di Tipi Personalizzati per la Validazione
Prendiamo l'idea di usare il sistema di tipi di Rust per assicurarci di avere un valore valido un passo avanti e guardiamo alla creazione di un tipo personalizzato per la validazione. Ricorda il gioco d'ipotesi nel Capitolo 2 in cui il nostro codice chiedeva all'utente di indovinare un numero tra 1 e 100. Non abbiamo mai validato che l'ipotesi dell'utente fosse tra quei numeri prima di controllarla contro il nostro numero segreto; abbiamo solo validato che l'ipotesi fosse positiva. In questo caso, le conseguenze non erano molto gravi: la nostra risposta di "Troppo alto" o "Troppo basso" sarebbe comunque stata corretta. Ma sarebbe un miglioramento utile guidare l'utente verso ipotesi valide e avere un comportamento diverso quando l'utente ipotizza un numero fuori dal range rispetto a quando l'utente digita, per esempio, lettere.
Un modo per fare questo sarebbe analizzare l'ipotesi come un i32
invece di solo un u32
per consentire potenzialmente numeri negativi, e poi aggiungere un controllo per il numero che sia nel range, così:
Nome del file: src/main.rs
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
loop {
// --snip--
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: i32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
if guess < 1 || guess > 100 {
println!("The secret number will be between 1 and 100.");
continue;
}
match guess.cmp(&secret_number) {
// --snip--
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
L'espressione if
controlla se il nostro valore è fuori dal range, informa l'utente del problema e chiama continue
per iniziare la prossima iterazione del ciclo e chiedere un'altra ipotesi. Dopo l'espressione if
, possiamo procedere con i confronti tra guess
e il numero segreto sapendo che guess
è tra 1 e 100.
Tuttavia, questa non è una soluzione ideale: se fosse assolutamente critico che il programma operasse solo su valori tra 1 e 100, e avesse molte funzioni con questo requisito, avere un controllo come questo in ogni funzione sarebbe tedioso (e potrebbe influire sulle prestazioni).
Invece, possiamo creare un nuovo tipo e mettere le convalide in una funzione per creare un'istanza del tipo piuttosto che ripetere le convalide ovunque. In questo modo, è sicuro per le funzioni utilizzare il nuovo tipo nelle loro firme e utilizzare con sicurezza i valori che ricevono. Elenco 9-13 mostra un modo per definire un tipo Guess
che creerà solo un'istanza di Guess
se la funzione new
riceve un valore tra 1 e 100.
Nome del file: src/lib.rs
#![allow(unused)] fn main() { {{#rustdoc_include ../listings/ch09-error-handling/listing-09-13/src/lib.rs}} }
Per prima cosa definiamo una struct chiamata Guess
che ha un campo chiamato value
che contiene un i32
. Questo è dove sarà memorizzato il numero.
Poi implementiamo una funzione associata chiamata new
su Guess
che crea istanze di valori Guess
. La funzione new
è definita per avere un parametro chiamato value
di tipo i32
e per restituire un Guess
. Il codice nel corpo della funzione new
testa value
per assicurarsi che sia tra 1 e 100. Se value
non passa questo test, facciamo una chiamata panic!
, che avviserà il programmatore che sta scrivendo il codice chiamante che ha un bug che deve risolvere, perché creare un Guess
con un value
fuori da questo range violerebbe il contratto su cui fa affidamento Guess::new
. Le condizioni in cui Guess::new
potrebbe andare in panico dovrebbero essere discusse nella documentazione dell'API pubblica; tratteremo le convenzioni di documentazione che indicano la possibilità di un panic!
nella documentazione dell'API che crei nel Capitolo 14. Se value
passa il test, creiamo un nuovo Guess
con il campo value
impostato sul parametro value
e restituiamo il Guess
.
Successivamente, implementiamo un metodo chiamato value
che prende in prestito self
, non ha altri parametri e restituisce un i32
. Questo tipo di metodo è talvolta chiamato getter perché il suo scopo è ottenere qualche dato dai suoi campi e restituirlo. Questo metodo pubblico è necessario perché il campo value
della struct Guess
è privato. È importante che il campo value
sia privato in modo che il codice che utilizza la struct Guess
non possa impostare direttamente value
: il codice al di fuori del modulo deve utilizzare la funzione Guess::new
per creare un'istanza di Guess
, garantendo così che non vi sia modo per un Guess
di avere un value
che non è stato controllato dalle condizioni nella funzione Guess::new
.
Una funzione che ha un parametro o restituisce solo numeri tra 1 e 100 potrebbe quindi dichiarare nella sua firma che accetta o restituisce un Guess
piuttosto che un i32
e non avrebbe bisogno di fare alcun controllo aggiuntivo nel suo corpo.
Sommario
Le funzionalità di gestione degli errori di Rust sono progettate per aiutarti a scrivere codice più robusto. La macro panic!
segnala che il tuo programma è in uno stato che non può gestire e ti permette di dire al processo di fermarsi invece di tentare di procedere con valori non validi o errati. L'enum Result
utilizza il sistema di tipi di Rust per indicare che le operazioni potrebbero fallire in un modo da cui il tuo codice potrebbe recuperare. Puoi usare Result
per dire al codice che chiama il tuo codice che deve gestire il successo potenziale o il fallimento. Usare panic!
e Result
nelle situazioni appropriate renderà il tuo codice più affidabile di fronte a problemi inevitabili.
Ora che hai visto modi utili in cui la libreria standard usa i generici con gli enum Option
e Result
, parleremo di come funzionano i generici e di come puoi usarli nel tuo codice.
Tipi Generici, Traits e Lifetimes
Ogni linguaggio di programmazione ha strumenti per gestire efficacemente la duplicazione di concetti. In Rust, uno di questi strumenti è rappresentato dai generics: sostituti astratti per tipi concreti o altre proprietà. Possiamo esprimere il comportamento dei generics o come essi si relazionano ad altri generics senza sapere cosa ci sarà al loro posto durante la compilazione e l'esecuzione del codice.
Le funzioni possono prendere parametri di qualche tipo generico, invece di un tipo concreto
come i32
o String
, nello stesso modo in cui prendono parametri con valori sconosciuti per eseguire lo stesso codice su più valori concreti. In effetti, abbiamo già usato i generics nel Capitolo 6 con Option<T>
, nel Capitolo 8 con Vec<T>
e HashMap<K, V>
, e nel Capitolo 9 con Result<T, E>
. In questo capitolo, esplorerai come definire i tuoi tipi, funzioni e metodi con i generics!
Prima esamineremo come estrarre una funzione per ridurre la duplicazione del codice. Utilizzeremo poi la stessa tecnica per creare una funzione generica partendo da due funzioni che differiscono solo nei tipi dei loro parametri. Spiegheremo anche come usare i tipi generici nelle definizioni di struct ed enum.
Successivamente imparerai come usare i traits per definire il comportamento in modo generico. Puoi combinare traits con tipi generici per vincolare un tipo generico ad accettare solo quei tipi che hanno un comportamento particolare, anziché qualsiasi tipo.
Infine, discuteremo dei lifetimes: una varietà di generics che forniscono al compilatore informazioni su come le references si relazionano tra loro. I lifetimes ci permettono di fornire al compilatore informazioni sufficienti sui valori presi in prestito in modo che possa garantire che le references saranno valide in più situazioni rispetto a quanto potrebbe fare senza il nostro aiuto.
Rimozione della duplicità estraendo una funzione
I generics ci permettono di sostituire tipi specifici con un segnaposto che rappresenta più tipi per rimuovere la duplicazione del codice. Prima di addentrarci nella sintassi dei generics, vediamo come rimuovere la duplicazione in modo che non implichi tipi generici estraendo una funzione che sostituisca valori specifici con un segnaposto che rappresenta più valori. Useremo quindi la stessa tecnica per estrarre una funzione generica! Vedendo come riconoscere il codice duplicato che puoi estrarre in una funzione, inizierai a riconoscere il codice duplicato che può usare i generics.
Inizieremo con il breve programma nella Listing 10-1 che trova il numero più grande in una lista.
Nome del file: src/main.rs
fn main() { let number_list = vec![34, 50, 25, 100, 65]; let mut largest = &number_list[0]; for number in &number_list { if number > largest { largest = number; } } println!("The largest number is {}", largest); assert_eq!(*largest, 100); }
Memorizziamo una lista di interi nella variabile number_list
e mettiamo
un riferimento al primo numero della lista in una variabile chiamata largest
. Iteriamo quindi
attraverso tutti i numeri nella lista, e se il numero corrente è maggiore del
numero memorizzato in largest
, sostituiamo il riferimento in quella variabile.
Tuttavia, se il numero corrente è minore o uguale al numero più grande visto
finora, la variabile non cambia e il codice passa al numero successivo
nella lista. Dopo aver considerato tutti i numeri nella lista, largest
dovrebbe riferirsi al numero più grande, che in questo caso è 100.
Ora ci è stato chiesto di trovare il numero più grande in due diverse liste di numeri. Per farlo, possiamo scegliere di duplicare il codice nella Listing 10-1 e usare la stessa logica in due posti diversi nel programma, come mostrato nella Listing 10-2.
Nome del file: src/main.rs
fn main() { let number_list = vec![34, 50, 25, 100, 65]; let mut largest = &number_list[0]; for number in &number_list { if number > largest { largest = number; } } println!("The largest number is {}", largest); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; let mut largest = &number_list[0]; for number in &number_list { if number > largest { largest = number; } } println!("The largest number is {}", largest); }
Sebbene questo codice funzioni, duplicare il codice è tedioso e soggetto ad errori. Dobbiamo anche ricordarci di aggiornare il codice in più punti quando vogliamo cambiarlo.
Per eliminare questa duplicazione, creeremo un'astrazione definendo una funzione che opera su qualsiasi lista di interi passata come parametro. Questa soluzione rende il nostro codice più chiaro e ci permette di esprimere il concetto di trovare il numero più grande in una lista in modo astratto.
Nella Listing 10-3, estraiamo il codice che trova il numero più grande in una
funzione chiamata largest
. Chiameremo poi la funzione per trovare il numero più
grande nelle due liste della Listing 10-2. Potremmo anche usare la funzione
su qualsiasi altra lista di valori i32
che potremmo avere in futuro.
Nome del file: src/main.rs
fn largest(list: &[i32]) -> &i32 { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest(&number_list); println!("The largest number is {}", result); assert_eq!(*result, 100); let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8]; let result = largest(&number_list); println!("The largest number is {}", result); assert_eq!(*result, 6000); }
La funzione largest
ha un parametro chiamato list
, che rappresenta qualsiasi
slice concreta di valori i32
che potremmo passare alla funzione. Di conseguenza,
quando chiamiamo la funzione, il codice viene eseguito sui valori specifici che passiamo.
In sintesi, ecco i passaggi che abbiamo seguito per cambiare il codice da Listing 10-2 a Listing 10-3:
- Identificare il codice duplicato.
- Estrarre il codice duplicato nel corpo della funzione e specificare gli input e i valori di ritorno di quel codice nella firma della funzione.
- Aggiornare le due istanze di codice duplicato per chiamare la funzione invece.
Successivamente, useremo questi stessi passaggi con i generics per ridurre la duplicazione del codice.
Nello stesso modo in cui il corpo della funzione può operare su un list
astratto anziché su valori specifici, i generics permettono al codice di operare su tipi astratti.
Ad esempio, supponiamo di avere due funzioni: una che trova l'elemento più grande in una slice di
valori i32
e una che trova l'elemento più grande in una slice di valori char
.
Come potremmo eliminare quella duplicazione? Scopriamolo!
Tipi di Dati Generici
Usiamo i generics per creare definizioni per elementi come firme di funzioni o structs, che possiamo poi utilizzare con molti tipi di dati concreti diversi. Vediamo prima come definire funzioni, structs, enums e metodi usando i generics. Poi discuteremo come i generics influenzano le prestazioni del codice.
Nelle Definizioni di Funzioni
Quando definiamo una funzione che utilizza i generics, posizioniamo i generics nella firma della funzione dove di solito specificheremmo i tipi di dati dei parametri e il valore di ritorno. Così facendo, rendiamo il nostro codice più flessibile e forniamo più funzionalità ai chiamanti della nostra funzione evitando la duplicazione del codice.
Continuando con la nostra funzione largest
, il Listing 10-4 mostra due funzioni che
trovano entrambe il valore più grande in una slice. Poi le combineremo in un'unica
funzione che utilizza i generics.
Nome del file: src/main.rs
fn largest_i32(list: &[i32]) -> &i32 { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn largest_char(list: &[char]) -> &char { let mut largest = &list[0]; for item in list { if item > largest { largest = item; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest_i32(&number_list); println!("The largest number is {}", result); assert_eq!(*result, 100); let char_list = vec!['y', 'm', 'a', 'q']; let result = largest_char(&char_list); println!("The largest char is {}", result); assert_eq!(*result, 'y'); }
La funzione largest_i32
è quella estratta nel Listing 10-3 che trova
il più grande i32
in una slice. La funzione largest_char
trova il più grande
char
in una slice. I corpi delle funzioni hanno lo stesso codice, quindi eliminiamo
la duplicazione introducendo un parametro di tipo generico in un'unica funzione.
Per parametrizzare i tipi in una nuova funzione singola, dobbiamo nominare il parametro di tipo,
proprio come facciamo per i parametri di valore di una funzione. Puoi usare
qualsiasi identificatore come nome del parametro di tipo. Ma useremo T
perché, per
convenzione, i nomi dei parametri di tipo in Rust sono brevi, spesso solo una lettera, e
la convenzione di denominazione dei tipi in Rust è UpperCamelCase. Breve per tipo, T
è la
scelta predefinita della maggior parte dei programmatori Rust.
Quando usiamo un parametro nel corpo della funzione, dobbiamo dichiarare il
nome del parametro nella firma affinché il compilatore sappia cosa significa quel nome.
Allo stesso modo, quando usiamo un nome di parametro di tipo in una firma di funzione, dobbiamo dichiarare il nome del parametro di tipo prima di usarlo. Per definire la funzione generica
largest
, posizioniamo le dichiarazioni del nome del tipo tra parentesi angolari,
<>
, tra il nome della funzione e l'elenco dei parametri, così:
fn largest<T>(list: &[T]) -> &T {
Leggiamo questa definizione come: la funzione largest
è generica su un tipo
T
. Questa funzione ha un parametro chiamato list
, che è una slice di valori
di tipo T
. La funzione largest
restituirà un riferimento a un valore dello
stesso tipo T
.
Il Listing 10-5 mostra la definizione combinata della funzione largest
utilizzando il tipo generico nella sua firma. Il listing mostra anche come possiamo chiamare la funzione con una slice di valori i32
o char
. Nota che questo codice non si compilerà ancora, ma lo correggeremo più tardi in questo capitolo.
Nome del file: src/main.rs
fn largest<T>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is {}", result);
let char_list = vec!['y', 'm', 'a', 'q'];
let result = largest(&char_list);
println!("The largest char is {}", result);
}
Se compiliamo questo codice ora, otterremo questo errore:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0369]: binary operation `>` cannot be applied to type `&T`
--> src/main.rs:5:17
|
5 | if item > largest {
| ---- ^ ------- &T
| |
| &T
|
help: consider restricting type parameter `T`
|
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> &T {
| ++++++++++++++++++++++
For more information about this error, try `rustc --explain E0369`.
error: could not compile `chapter10` due to previous error
Il testo di aiuto menziona std::cmp::PartialOrd
, che è un trait, e parleremo
dei traits nella prossima sezione. Per ora, sappi che questo errore
indica che il corpo di largest
non funzionerà per tutti i possibili tipi che T
potrebbe essere. Poiché vogliamo confrontare valori di tipo T
nel corpo, possiamo
usare solo tipi i cui valori possono essere ordinati. Per abilitare i confronti, la libreria standard ha il trait std::cmp::PartialOrd
che puoi implementare sui tipi
(vedi l'Appendice C per ulteriori informazioni su questo trait). Seguendo il suggerimento del testo di aiuto, restringiamo i tipi validi per T
a solo quelli che implementano PartialOrd
e questo esempio si compila, perché la libreria standard
implementa PartialOrd
sia su i32
che su char
.
Nelle Definizioni di Struct
Possiamo anche definire struct per utilizzare un parametro di tipo generico in uno o più
campi usando la sintassi <>
. Il Listing 10-6 definisce una struct Point<T>
per contenere
valori di coordinate x
e y
di qualsiasi tipo.
Nome del file: src/main.rs
struct Point<T> { x: T, y: T, } fn main() { let integer = Point { x: 5, y: 10 }; let float = Point { x: 1.0, y: 4.0 }; }
La sintassi per usare i generics nelle definizioni di struct è simile a quella utilizzata nelle definizioni di funzioni. Prima dichiariamo il nome del parametro di tipo dentro parentesi angolari subito dopo il nome della struct. Poi usiamo il tipo generico nella definizione della struct dove altrimenti specificheremmo tipi di dati concreti.
Nota che poiché abbiamo utilizzato un solo tipo generico per definire Point<T>
, questa
definizione dice che la struct Point<T>
è generica su un tipo T
, e
i campi x
e y
sono entrambi di quel tipo, qualunque esso sia. Se
creiamo un'istanza di un Point<T>
che ha valori di tipi diversi, come nel
Listing 10-7, il nostro codice non si compilerà.
Nome del file: src/main.rs
struct Point<T> {
x: T,
y: T,
}
fn main() {
let wont_work = Point { x: 5, y: 4.0 };
}
In questo esempio, quando assegniamo il valore intero 5
a x
, facciamo sapere al
compilatore che il tipo generico T
sarà un intero per questa istanza di
Point<T>
. Poi, quando specifichiamo 4.0
per y
, che abbiamo definito per avere lo
stesso tipo di x
, otterremo un errore di corrispondenza di tipo come questo:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0308]: mismatched types
--> src/main.rs:7:38
|
7 | let wont_work = Point { x: 5, y: 4.0 };
| ^^^ expected integer, found floating-point number
For more information about this error, try `rustc --explain E0308`.
error: could not compile `chapter10` due to previous error
Per definire una struct Point
dove x
e y
sono entrambi generici ma potrebbero avere tipi diversi, possiamo usare più parametri di tipo generici. Per esempio, nel
Listing 10-8, cambiamo la definizione di Point
per essere generica sui tipi T
e U
dove x
è di tipo T
e y
è di tipo U
.
Nome del file: src/main.rs
struct Point<T, U> { x: T, y: U, } fn main() { let both_integer = Point { x: 5, y: 10 }; let both_float = Point { x: 1.0, y: 4.0 }; let integer_and_float = Point { x: 5, y: 4.0 }; }
Ora tutte le istanze di Point
mostrate sono permesse! Puoi usare quanti parametri
di tipo generici vuoi in una definizione, ma usarne più di pochi rende
difficile leggere il codice. Se scopri di aver bisogno di molti tipi generici
nel tuo codice, potrebbe indicare che il tuo codice ha bisogno
di essere ristrutturato in pezzi più piccoli.
Nelle Definizioni di Enum
Come abbiamo fatto con le structs, possiamo definire enums per contenere tipi di dati generici nelle loro varianti. Diamo un'altra occhiata alla enum Option<T>
che la libreria standard fornisce, che abbiamo utilizzato nel Capitolo 6:
#![allow(unused)] fn main() { enum Option<T> { Some(T), None, } }
Questa definizione dovrebbe ora avere più senso per te. Come puoi vedere, l'enum
Option<T>
è generica sul tipo T
e ha due varianti: Some
, che
contiene un valore di tipo T
, e una variante None
che non contiene alcun valore.
Usando l'enum Option<T>
, possiamo esprimere il concetto astratto di un
valore opzionale, e poiché Option<T>
è generica, possiamo usare questa astrazione
indipendentemente dal tipo del valore opzionale.
Gli enums possono anche usare più tipi generici. La definizione dell'enum Result
che abbiamo utilizzato nel Capitolo 9 ne è un esempio:
#![allow(unused)] fn main() { enum Result<T, E> { Ok(T), Err(E), } }
L'enum Result
è generica su due tipi, T
ed E
, e ha due varianti:
Ok
, che contiene un valore di tipo T
, e Err
, che contiene un valore di tipo
E
. Questa definizione rende conveniente usare l'enum Result
ovunque abbiamo
un'operazione che potrebbe avere successo (restituire un valore di qualche tipo T
) o fallire
(restituire un errore di qualche tipo E
). In effetti, questo è ciò che abbiamo usato per aprire un
file nel Listing 9-3, dove T
è stato riempito con il tipo std::fs::File
quando il file è stato aperto con successo e E
è stato riempito con il tipo
std::io::Error
quando ci sono stati problemi nell'aprire il file.
Quando riconosci situazioni nel tuo codice con più definizioni di struct o enum che differiscono solo nei tipi dei valori che contengono, puoi evitare duplicazioni usando i tipi generici.
Nelle Definizioni di Metodi
Possiamo implementare metodi su structs e enums (come abbiamo fatto nel Capitolo 5) e usare
tipi generici anche nelle loro definizioni. Il Listing 10-9 mostra la struct Point<T>
che abbiamo definito nel Listing 10-6 con un metodo chiamato x
implementato su di essa.
Nome del file: src/main.rs
struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } } fn main() { let p = Point { x: 5, y: 10 }; println!("p.x = {}", p.x()); }
Qui, abbiamo definito un metodo chiamato x
su Point<T>
che restituisce un riferimento
al dato nel campo x
.
Nota che dobbiamo dichiarare T
subito dopo impl
affinché possiamo usare T
per specificare
che stiamo implementando metodi sul tipo Point<T>
. Dichiarando T
come tipo generico dopo impl
, Rust può identificare che il tipo nelle parentesi
angolari in Point
è un tipo generico anziché un tipo concreto. Avremmo
potuto scegliere un nome diverso per questo parametro generico rispetto a quello dichiarato nella definizione della struct, ma usare lo stesso nome è convenzionale. I metodi scritti dentro un impl
che dichiara il tipo generico saranno definiti su qualsiasi istanza del tipo, qualunque tipo concreto finisca per sostituire il tipo generico.
Possiamo anche specificare vincoli sui tipi generici quando definiamo metodi sul
tipo. Potremmo, per esempio, implementare metodi solo su istanze di Point<f32>
anziché su istanze di Point<T>
con qualsiasi tipo generico. Nel Listing 10-10 usiamo
il tipo concreto f32
, il che significa che non dichiariamo alcun tipo dopo impl
.
Nome del file: src/main.rs
struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } } impl Point<f32> { fn distance_from_origin(&self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() } } fn main() { let p = Point { x: 5, y: 10 }; println!("p.x = {}", p.x()); }
Questo codice significa che il tipo Point<f32>
avrà un metodo distance_from_origin
;
altre istanze di Point<T>
dove T
non è di tipo f32
non avranno questo metodo
definito. Il metodo misura quanto lontano è il nostro punto dal
punto alle coordinate (0.0, 0.0) e utilizza operazioni matematiche che sono
disponibili solo per i tipi a virgola mobile.
I parametri di tipo generico in una definizione di struct non sono sempre gli stessi di quelli che usi nelle firme dei metodi di quella stessa struct. Il Listing 10-11 usa i tipi generici X1
e Y1
per la struct Point
e X2
e Y2
per la firma del metodo mixup
per rendere l'esempio più chiaro. Il metodo crea una nuova istanza di Point
con il valore x
dalla self
Point
(di tipo X1
) e il valore y
dalla Point
passata
(in di tipo Y2
).
Nome del file: src/main.rs
struct Point<X1, Y1> { x: X1, y: Y1, } impl<X1, Y1> Point<X1, Y1> { fn mixup<X2, Y2>(self, other: Point<X2, Y2>) -> Point<X1, Y2> { Point { x: self.x, y: other.y, } } } fn main() { let p1 = Point { x: 5, y: 10.4 }; let p2 = Point { x: "Hello", y: 'c' }; let p3 = p1.mixup(p2); println!("p3.x = {}, p3.y = {}", p3.x, p3.y); }
In main
, abbiamo definito un Point
che ha un i32
per x
(con valore 5
)
e un f64
per y
(con valore 10.4
). La variabile p2
è una struct Point
che ha una stringa slice per x
(con valore "Hello"
) e un char
per y
(con valore c
). Chiamare mixup
su p1
con l'argomento p2
ci dà p3
,
che avrà un i32
per x
perché x
deriva da p1
. La variabile p3
avrà un char
per y
perché y
deriva da p2
. La chiamata alla macro println!
stamperà p3.x = 5, p3.y = c
.
Lo scopo di questo esempio è dimostrare una situazione in cui alcuni
parametri generici sono dichiarati con impl
e alcuni sono dichiarati con la definizione del metodo. Qui, i parametri generici X1
e Y1
sono dichiarati dopo impl
perché vanno con la definizione della struct. I parametri generici X2
e Y2
sono dichiarati dopo fn mixup
perché sono rilevanti solo per il
metodo.
Prestazioni del Codice che Usa i Generics
Potresti chiederti se c'è un costo in tempo di esecuzione quando si utilizzano i parametri di tipo generici. La buona notizia è che usare tipi generici non renderà il tuo programma più lento di quanto sarebbe con tipi concreti.
Rust realizza questo eseguendo la monomorfizzazione del codice che utilizza generics al tempo di compilazione. Monomorfizzazione è il processo di trasformazione del codice generico in codice specifico riempiendo i tipi concreti che vengono utilizzati durante la compilazione. In questo processo, il compilatore esegue il contrario dei passaggi utilizzati per creare la funzione generica nel Listing 10-5: il compilatore analizza tutti i luoghi dove il codice generico viene chiamato e genera codice per i tipi concreti con cui il codice generico viene chiamato.
Vediamo come funziona utilizzando l'enum generico Option<T>
della
libreria standard:
#![allow(unused)] fn main() { let integer = Some(5); let float = Some(5.0); }
Quando Rust compila questo codice, esegue la monomorfizzazione. Durante quel
processo, il compilatore legge i valori che sono stati utilizzati nelle istanze di Option<T>
e identifica due tipi di Option<T>
: uno è i32
e l'altro
è f64
. Così, espande la definizione generica di Option<T>
in due
definizioni specializzate per i32
e f64
, sostituendo così la definizione
generica con quelle specifiche.
La versione monomorfizzata del codice sembra simile a quanto segue (il compilatore usa nomi diversi da quelli che stiamo usando qui per illustrazione):
Nome del file: src/main.rs
enum Option_i32 { Some(i32), None, } enum Option_f64 { Some(f64), None, } fn main() { let integer = Option_i32::Some(5); let float = Option_f64::Some(5.0); }
La Option<T>
generica viene sostituita con le definizioni specifiche create
dal compilatore. Poiché Rust compila il codice generico in codice che specifica il
tipo in ciascuna istanza, non paghiamo alcun costo in tempo di esecuzione per
usare i generics. Quando il codice viene eseguito, funziona proprio come farebbe
se avessimo duplicato ciascuna definizione a mano. Il processo di monomorfizzazione
rende i generics di Rust estremamente efficienti in fase di esecuzione.
Trait: Definire Comportamenti Condivisi
Un trait definisce la funzionalità che un determinato tipo ha e che può condividere con altri tipi. Possiamo usare i trait per definire comportamenti condivisi in modo astratto. Possiamo usare i trait bounds per specificare che un tipo generico può essere qualsiasi tipo che ha certi comportamenti.
Nota: I trait sono simili a una funzione spesso chiamata interfacce in altri linguaggi, sebbene con alcune differenze.
Definire un Trait
Il comportamento di un tipo consiste nei metodi che possiamo chiamare su quel tipo. Tipi diversi condividono lo stesso comportamento se possiamo chiamare gli stessi metodi su tutti questi tipi. Le definizioni dei trait sono un modo per raggruppare insieme le firme dei metodi per definire un insieme di comportamenti necessari per raggiungere uno scopo.
Per esempio, diciamo che abbiamo più struct che contengono vari tipi e quantità di testo: una struct NewsArticle
che contiene una notizia archiviata in una posizione particolare e un Tweet
che può avere, al massimo, 280 caratteri assieme a metadati che indicano se era un nuovo tweet, un retweet, o una risposta a un altro tweet.
Vogliamo creare una crate libreria aggregatrice di media chiamata aggregator
che possa mostrare riassunti di dati che potrebbero essere archiviati in unistanza di
NewsArticleo
Tweet. Per fare questo, abbiamo bisogno di un sommario da ogni tipo, e richiederemo quel sommario chiamando un metodo
summarizesu un'istanza. Listing 10-12 mostra la definizione di un trait pubblico
Summary` che esprime questo comportamento.
Nome del file: src/lib.rs
pub trait Summary {
fn summarize(&self) -> String;
}
Qui dichiariamo un trait usando la parola chiave trait
e poi il nome del trait, che in questo caso è Summary
. Dichiariamo anche il trait come pub
affinché i crate che dipendono da questo crate possano utilizzare questo trait, come vedremo in alcuni esempi. Dentro le parentesi graffe, dichiariamo le firme dei metodi che descrivono i comportamenti dei tipi che implementano questo trait, che in questo caso è fn summarize(&self) -> String
.
Dopo la firma del metodo, invece di fornire una implementazione dentro parentesi graffe, usiamo un punto e virgola. Ogni tipo che implementa questo trait deve fornire il proprio comportamento personalizzato per il corpo del metodo. Il compilatore imporrà che qualsiasi tipo che ha il trait Summary
avrà il metodo summarize
definito con esattamente questa firma.
Un trait può avere più metodi nel suo corpo: le firme dei metodi sono elencate una per linea, e ogni linea termina in un punto e virgola.
Implementare un Trait su un Tipo
Ora che abbiamo definito le firme desiderate dei metodi del trait Summary
, possiamo implementarlo sui tipi nel nostro aggregatore di media. Listing 10-13 mostra un'implementazione del trait Summary
sulla struct NewsArticle
che utilizza il titolo, l'autore e la località per creare il valore di ritorno di summarize
. Per la struct Tweet
, definiamo summarize
come il nome utente seguito dall'intero testo del tweet, assumendo che il contenuto del tweet sia già limitato a 280 caratteri.
Nome del file: src/lib.rs
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
Implementare un trait su un tipo è simile a implementare metodi regolari. La differenza è che dopo impl
, mettiamo il nome del trait che vogliamo implementare, usiamo la parola chiave for
, e poi specifichiamo il nome del tipo per cui vogliamo implementare il trait. All'interno del blocco impl
, mettiamo le firme dei metodi che la definizione del trait ha definito. Invece di aggiungere un punto e virgola dopo ogni firma, utilizziamo parentesi graffe e riempiamo il corpo del metodo con il comportamento specifico che vogliamo che i metodi del trait abbiano per il tipo particolare.
Ora che la libreria ha implementato il trait Summary
su NewsArticle
e Tweet
, gli utenti del crate possono chiamare i metodi del trait sulle istanze di NewsArticle
e Tweet
nello stesso modo in cui chiamiamo metodi regolari. L'unica differenza è che l'utente deve portare il trait nello scope così come i tipi. Ecco un esempio di come un crate binario potrebbe utilizzare il nostro crate di libreria aggregator
:
use aggregator::{Summary, Tweet};
fn main() {
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
};
println!("1 new tweet: {}", tweet.summarize());
}
Questo codice stampa 1 new tweet: horse_ebooks: of course, as you probably already know, people
.
Altri crate che dipendono dal crate aggregator
possono anche portare il trait Summary
nello scope per implementare Summary
sui propri tipi. Una limitazione da notare è che possiamo implementare un trait su un tipo solo se o il trait o il tipo, o entrambi, sono locali al nostro crate. Per esempio, possiamo implementare trait della libreria standard come Display
su un tipo personalizzato come Tweet
come parte della funzionalità del nostro crate aggregator
perché il tipo Tweet
è locale al nostro crate aggregator
. Possiamo anche implementare Summary
su Vec<T>
nel nostro crate aggregator
perché il trait Summary
è locale al nostro crate aggregator
.
Ma non possiamo implementare trait esterni su tipi esterni. Per esempio, non possiamo implementare il trait Display
su Vec<T>
nel nostro crate aggregator
perché sia Display
che Vec<T>
sono definiti nella libreria standard e non sono locali al nostro crate aggregator
. Questa restrizione è parte di una proprietà chiamata coesione, e più specificamente la regola dell'orfano, così chiamata perché il tipo padre non è presente. Questa regola garantisce che il codice di altre persone non possa rompere il tuo codice e viceversa. Senza la regola, due crate potrebbero implementare lo stesso trait per lo stesso tipo, e Rust non saprebbe quale implementazione usare.
Implementazioni Predefinite
A volte è utile avere un comportamento predefinito per alcuni o tutti i metodi in un trait invece di richiedere implementazioni per tutti i metodi su ogni tipo. Poi, mentre implementiamo il trait su un particolare tipo, possiamo mantenere o sovrascrivere il comportamento predefinito di ogni metodo.
Nel Listing 10-14, specifichiamo una stringa predefinita per il metodo summarize
del trait
Summary
invece di definire solo la firma del metodo, come abbiamo fatto nel Listing 10-12.
Nome del file: src/lib.rs
pub trait Summary {
fn summarize(&self) -> String {
String::from("(Read more...)")
}
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
Per utilizzare un’implementazione predefinita per riassumere le istanze di NewsArticle
,
specifichiamo un blocco impl
vuoto con impl Summary for NewsArticle {}
.
Anche se non stiamo più definendo direttamente il metodo summarize
su NewsArticle
,
abbiamo fornito un'implementazione predefinita e specificato che NewsArticle
implementa il trait Summary
. Di conseguenza, possiamo ancora chiamare il metodo summarize
su un'istanza di NewsArticle
, così:
use aggregator::{self, NewsArticle, Summary};
fn main() {
let article = NewsArticle {
headline: String::from("Penguins win the Stanley Cup Championship!"),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from(
"The Pittsburgh Penguins once again are the best \
hockey team in the NHL.",
),
};
println!("New article available! {}", article.summarize());
}
Questo codice stampa New article available! (Read more...)
.
Creare un'implementazione predefinita non richiede di cambiare nulla sull'implementazione di Summary
su Tweet
nel Listing 10-13. Il motivo è che la sintassi per sovrascrivere un’implementazione predefinita è la stessa della sintassi per implementare un metodo di trait che non ha un'implementazione predefinita.
Le implementazioni predefinite possono chiamare altri metodi nello stesso trait, anche se quegli altri metodi non hanno un'implementazione predefinita. In questo modo, un trait può fornire molta funzionalità utile e richiedere solo che gli implementatori specifichino una piccola parte di essa. Per esempio, potremmo definire il trait Summary
per avere un metodo summarize_author
la cui implementazione è richiesta, e poi definire un metodo summarize
che ha un'implementazione predefinita che chiama il metodo summarize_author
:
pub trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
}
Per utilizzare questa versione di Summary
, dobbiamo solo definire summarize_author
quando implementiamo il trait su un tipo:
pub trait Summary {
fn summarize_author(&self) -> String;
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
}
Dopo aver definito summarize_author
, possiamo chiamare summarize
sulle istanze della
struct Tweet
, e l'implementazione predefinita di summarize
chiamerà la definizione di summarize_author
che abbiamo fornito. Poiché abbiamo implementato summarize_author
, il trait Summary
ci ha dato il comportamento del metodo summarize
senza richiederci di scrivere altro codice. Ecco come appare:
use aggregator::{self, Summary, Tweet};
fn main() {
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
};
println!("1 new tweet: {}", tweet.summarize());
}
Questo codice stampa 1 new tweet: (Read more from @horse_ebooks...)
.
Nota che non è possibile chiamare l'implementazione predefinita da un'implementazione sovrascritta di quello stesso metodo.
Trait come Parametri
Ora che sai come definire e implementare i trait, possiamo esplorare come usare i trait per definire funzioni che accettano molti tipi diversi. Useremo il trait Summary
che abbiamo implementato sui tipi NewsArticle
e Tweet
nel Listing 10-13 per definire una funzione notify
che chiama il metodo summarize
sul suo parametro item
, che è di un tipo che implementa il trait Summary
. Per farlo, usiamo la sintassi impl Trait
, come questo:
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
pub fn notify(item: &impl Summary) {
println!("Breaking news! {}", item.summarize());
}
Invece di un tipo concreto per il parametro item
, specifichiamo la parola chiave impl
e il nome del trait. Questo parametro accetta qualsiasi tipo che implementi il trait specificato. Nel corpo di notify
, possiamo chiamare qualsiasi metodo su item
che proviene dal trait Summary
, come summarize
. Possiamo chiamare notify
e passare qualsiasi istanza di NewsArticle
o Tweet
. Il codice che chiama la funzione con qualsiasi altro tipo, come una String
o un i32
, non compila perché quei tipi non implementano Summary
.
Sintassi Trait Bound
La sintassi impl Trait
funziona per casi semplici ma è effettivamente una semplificazione sintattica per una forma più lunga conosciuta come trait bound; sembra così:
pub fn notify<T: Summary>(item: &T) {
println!("Breaking news! {}", item.summarize());
}
Questa forma più lunga è equivalente all'esempio nella sezione precedente ma è più verbosa. Inseriamo i bound trait con la dichiarazione del parametro di tipo generico dopo un due punti e all'interno di parentesi angolari.
La sintassi impl Trait
è conveniente e rende il codice più conciso in casi semplici, mentre la sintassi completa dei trait bound può esprimere maggiore complessità in altri casi. Per esempio, possiamo avere due parametri che implementano Summary
. Farlo con la sintassi impl Trait
sembra così:
pub fn notify(item1: &impl Summary, item2: &impl Summary) {
Usare impl Trait
è appropriato se vogliamo che questa funzione permetta a item1
e item2
di avere tipi diversi (purché entrambi i tipi implementino Summary
). Se vogliamo costringere entrambi i parametri ad avere lo stesso tipo, tuttavia, dobbiamo usare un trait bound, così:
pub fn notify<T: Summary>(item1: &T, item2: &T) {
Il tipo generico T
specificato come tipo dei parametri item1
e item2
vincola la funzione in modo tale che il tipo concreto del valore passato come argomento per item1
e item2
debba essere lo stesso.
Specificare Più Trait Bound con la Sintassi +
Possiamo anche specificare più di un trait bound. Supponiamo di voler utilizzare la formattazione display oltre a summarize
su item
: specifichiamo nella definizione di notify
che item
deve implementare sia Display
che Summary
. Possiamo farlo usando la sintassi +
:
pub fn notify(item: &(impl Summary + Display)) {
La sintassi +
è valida anche con i trait bound sui tipi generici:
pub fn notify<T: Summary + Display>(item: &T) {
Con i due trait bound specificati, il corpo di notify
può chiamare summarize
e usare {}
per formattare item
.
Trait Bound più Chiari con Le Clausole where
Utilizzare troppi trait bound ha aspetti negativi. Ogni generico ha i suoi trait bound, quindi le funzioni con più parametri di tipo generico possono contenere molte informazioni sui trait bound tra il nome della funzione e la sua lista di parametri, rendendo difficile la lettura della firma della funzione. Per questo motivo, Rust ha una sintassi alternativa per specificare i trait bound all'interno di una clausola where
dopo la firma della funzione. Quindi, invece di scrivere questo:
fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {
possiamo usare una clausola where
, così:
fn some_function<T, U>(t: &T, u: &U) -> i32
where
T: Display + Clone,
U: Clone + Debug,
{
unimplemented!()
}
La firma di questa funzione è meno affollata: il nome della funzione, la lista dei parametri e il tipo di ritorno sono vicini tra loro, simili a una funzione senza numerosi trait bound.
Restituire Tipi che Implementano Trait
Possiamo anche usare la sintassi impl Trait
nella posizione di ritorno per restituire un valore di un tipo che implementa un trait, come mostrato qui:
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
fn returns_summarizable() -> impl Summary {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}
Usando impl Summary
come tipo di ritorno, specifichiamo che la funzione
returns_summarizable
restituisce un tipo che implementa il trait Summary
senza nominare il tipo concreto. In questo caso, returns_summarizable
restituisce un Tweet
, ma il codice che chiama questa funzione non ha bisogno di saperlo.
La capacità di specificare un tipo di ritorno solo tramite il trait che implementa è particolarmente utile nel contesto delle closure e degli iteratori, che copriamo nel Capitolo 13. Le closure e gli iteratori creano tipi che solo il compilatore conosce o tipi che sono molto lunghi da specificare. La sintassi impl Trait
ti permette di specificare concisamente che una funzione restituisce un tipo che implementa il trait Iterator
senza bisogno di scrivere un tipo molto lungo.
Tuttavia, puoi usare impl Trait
solo se stai restituendo un singolo tipo. Ad esempio, questo codice che restituisce un NewsArticle
o un Tweet
con il tipo di ritorno specificato come impl Summary
non funzionerebbe:
pub trait Summary {
fn summarize(&self) -> String;
}
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} ({})", self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
}
fn returns_summarizable(switch: bool) -> impl Summary {
if switch {
NewsArticle {
headline: String::from(
"Penguins win the Stanley Cup Championship!",
),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from(
"The Pittsburgh Penguins once again are the best \
hockey team in the NHL.",
),
}
} else {
Tweet {
username: String::from("horse_ebooks"),
content: String::from(
"of course, as you probably already know, people",
),
reply: false,
retweet: false,
}
}
}
Restituire sia un NewsArticle
che un Tweet
non è consentito a causa delle restrizioni su come la sintassi impl Trait
è implementata nel compilatore. Copriremo come scrivere una funzione con questo comportamento nella sezione “Usare Oggetti Trait che Consentono Valori di Diversi Tipi” del Capitolo 17.
Utilizzare i Trait Bound per Implementare Condizionalmente Met# Definizioni di Metodi
Utilizzando un trait bound
con un blocco impl
che usa parametri di tipo generico,
possiamo implementare metodi condizionalmente per tipi che implementano i trait
specificati.
Ad esempio, il tipo Pair<T>
in Listing 10-15 implementa sempre la funzione new
per restituire una nuova istanza di Pair<T>
(ricorda dalla sezione “Defining Methods” del Capitolo 5 che Self
è un alias di tipo per il tipo del blocco impl
, che in questo caso è Pair<T>
). Ma nel prossimo blocco impl
, Pair<T>
implementa il metodo cmp_display
solo se il suo tipo interno T
implementa il PartialOrd
trait che abilita il confronto e il Display
trait che abilita la stampa.
Filename: src/lib.rs
use std::fmt::Display;
struct Pair<T> {
x: T,
y: T,
}
impl<T> Pair<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl<T: Display + PartialOrd> Pair<T> {
fn cmp_display(&self) {
if self.x >= self.y {
println!("The largest member is x = {}", self.x);
} else {
println!("The largest member is y = {}", self.y);
}
}
}
Possiamo anche implementare condizionatamente un trait per qualsiasi tipo che ne implementi un altro. Le implementazioni di un trait su qualsiasi tipo che soddisfi i trait bounds sono chiamate implementazioni globali e sono ampiamente utilizzate nella libreria standard di Rust. Ad esempio, la libreria standard implementa il ToString
trait su qualsiasi tipo che implementi il Display
trait. Il blocco impl
nella libreria standard è simile a questo codice:
impl<T: Display> ToString for T {
// --snip--
}
Poiché la libreria standard ha questa implementazione globale, possiamo chiamare il metodo to_string
definito dal ToString
trait su qualsiasi tipo che implementi il Display
trait. Ad esempio, possiamo trasformare gli interi nei loro corrispondenti valori String
in questo modo perché gli interi implementano Display
:
#![allow(unused)] fn main() { let s = 3.to_string(); }
Le implementazioni globali compaiono nella documentazione del trait nella sezione "Implementors".
I trait e i trait bounds ci permettono di scrivere codice che usa parametri di tipo generico per ridurre la duplicazione ma specificare anche al compilatore che vogliamo che il tipo generico abbia un particolare comportamento. Il compilatore può quindi utilizzare le informazioni del trait bound per verificare che tutti i tipi concreti utilizzati con il nostro codice forniscano il comportamento corretto. Nei linguaggi dinamicamente tipizzati, otterremmo un errore a runtime se chiamassimo un metodo su un tipo che non ha definito il metodo. Ma Rust sposta questi errori al tempo di compilazione, quindi siamo costretti a risolvere i problemi prima che il nostro codice possa essere eseguito. Inoltre, non dobbiamo scrivere codice che controlla il comportamento a tempo di esecuzione perché l'abbiamo già verificato a tempo di compilazione. Fare così migliora le prestazioni senza dover rinunciare alla flessibilità dei generici.
Validare le Riferimenti con i Lifetimes
I Lifetimes sono un altro tipo di generico che abbiamo già utilizzato. Piuttosto che garantire che un tipo abbia il comportamento desiderato, i lifetimes garantiscono che i riferimenti siano validi tanto a lungo quanto necessario.
Un dettaglio che non abbiamo discusso nella sezione "References and Borrowing" nel Capitolo 4 è che ogni riferimento in Rust ha un lifetime, che è l'ambito per cui quel riferimento è valido. La maggior parte delle volte, i lifetimes sono impliciti e dedotti, proprio come la maggior parte delle volte, i tipi sono dedotti. Dobbiamo annotare i tipi solo quando sono possibili tipi multipli. In modo simile, dobbiamo annotare i lifetimes quando i lifetimes dei riferimenti potrebbero essere correlati in alcuni modi diversi. Rust ci richiede di annotare le relazioni usando parametri lifetime generici per garantire che i riferimenti effettivi utilizzati a runtime saranno sicuramente validi.
Annotare i lifetimes non è un concetto che la maggior parte degli altri linguaggi di programmazione ha, quindi questo sembrerà poco familiare. Sebbene non copriremo i lifetimes nella loro interezza in questo capitolo, discuteremo dei modi comuni in cui potresti incontrare la sintassi dei lifetimes così che tu possa familiarizzare con il concetto.
Prevenire Riferimenti Pendenti con i Lifetimes
Lo scopo principale dei lifetimes è prevenire i riferimenti pendenti, che causano a program di riferirsi a dati diversi dai dati che intende referenziare. Considera il programma in Listing 10-16, che ha un ambito esterno e un ambito interno.
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("r: {}", r);
}
Nota: Gli esempi nei Listing 10-16, 10-17, e 10-23 dichiarano variabili senza assegnare loro un valore iniziale, così il nome della variabile esiste nell'ambito esterno. A prima vista, questo potrebbe sembrare in conflitto con il fatto che Rust non abbia valori nulli. Tuttavia, se proviamo a utilizzare una variabile prima di assegnarle un valore, otterremo un errore a tempo di compilazione, il che dimostra che Rust non permette effettivamente valori nulli.
L'ambito esterno dichiara una variabile chiamata r
senza valore iniziale, e l'ambito
interno dichiara una variabile chiamata x
con valore iniziale di 5
. All'interno
dell'ambito interno, tentiamo di assegnare il valore di r
come riferimento a x
. Poi
l'ambito interno termina, e tentiamo di stampare il valore in r
. Questo codice non
compila perché il valore a cui r
si riferisce è uscito dall'ambito prima
che proviamo a usarlo. Ecco il messaggio di errore:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `x` does not live long enough
--> src/main.rs:6:13
|
6 | r = &x;
| ^^ borrowed value does not live long enough
7 | }
| - `x` dropped here while still borrowed
8 |
9 | println!("r: {}", r);
| - borrow later used here
For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` due to previous error
Il messaggio di errore dice che la variabile x
"non vive abbastanza a lungo". La
ragione è che x
sarà fuori dall'ambito quando l'ambito interno termina alla linea 7.
Ma r
è ancora valido per l'ambito esterno; poiché il suo ambito è più ampio, diciamo
che "vive più a lungo". Se Rust permettesse a questo codice di funzionare, r
farebbe riferimento a memoria che è stata deallocata quando x
è uscito dall'ambito, e
qualsiasi cosa provassimo a fare con r
non funzionerebbe correttamente. Quindi come fa
Rust a determinare che questo codice non è valido? Utilizza un borrow checker.
Il Borrow Checker
Il compilatore Rust ha un borrow checker che confronta gli ambiti per determinare se tutti i prestiti sono validi. Il Listing 10-17 mostra lo stesso codice del Listing 10-16 ma con annotazioni che mostrano i lifetimes delle variabili.
fn main() {
let r; // ---------+-- 'a
// |
{ // |
let x = 5; // -+-- 'b |
r = &x; // | |
} // -+ |
// |
println!("r: {}", r); // |
} // ---------+
Qui, abbiamo annotato il lifetime di r
con 'a
e il lifetime di x
con 'b
. Come puoi vedere, l'ambito interno 'b
è molto più piccolo dell'ambito
lifetime esterno 'a
. A tempo di compilazione, Rust confronta la dimensione dei due
lifetimes e vede che r
ha un lifetime di 'a
ma fa riferimento a memoria
con un lifetime di 'b
. Il programma viene rigettato perché 'b
è inferiore a
'a
: il soggetto del riferimento non vive quanto il riferimento.
Il Listing 10-18 risolve il codice così che non ha un riferimento pendente e compila senza errori.
fn main() { let x = 5; // ----------+-- 'b // | let r = &x; // --+-- 'a | // | | println!("r: {}", r); // | | // --+ | } // ----------+
Qui, x
ha il lifetime 'b
, che in questo caso è più grande di 'a
. Questo
significa che r
può riferirsi a x
perché Rust sa che il riferimento in r
sarà
sempre valido mentre x
è valido.
Ora che sai quali sono i lifetimes dei riferimenti e come Rust analizza i lifetimes per garantire che i riferimenti saranno sempre validi, esploriamo i lifetimes generici dei parametri e dei valori di ritorno nel contesto delle funzioni.
Lifetimes Generici nelle Funzioni
Scriveremo una funzione che restituisce la più lunga di due stringhe slices. Questa
funzione prenderà due stringhe slices e restituirà una singola stringa slice. Dopo
aver implementato la funzione longest
, il codice nel Listing 10-19 dovrebbe
stampare The longest string is abcd
.
File: src/main.rs
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
Nota che vogliamo che la funzione prenda stringhe slices, che sono riferimenti,
piuttosto che stringhe, perché non vogliamo che la funzione longest
prenda
ownership dei suoi parametri. Consulta la sezione "String Slices as
Parameters" nel Capitolo 4
per una discussione più dettagliata sul motivo per cui i parametri che utilizziamo nel Listing 10-19 sono
quelli che vogliamo.
Se proviamo a implementare la funzione longest
come mostrato nel Listing 10-20, essa non
compilerà.
File: src/main.rs
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
Invece, otteniamo il seguente errore che parla di lifetimes:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0106]: missing lifetime specifier
--> src/main.rs:9:33
|
9 | fn longest(x: &str, y: &str) -> &str {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
|
9 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
| ++++ ++ ++ ++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `chapter10` due to previous error
Il messaggio di aiuto rivela che il tipo di ritorno ha bisogno di un parametro lifetime generico
perché Rust non può dire se il riferimento restituito si riferisce a
x
o y
. In realtà, non lo sappiamo nemmeno noi, perché il blocco if
nel corpo
di questa funzione restituisce un riferimento a x
e il blocco else
restituisce un
riferimento a y
!
Quando stiamo definendo questa funzione, non conosciamo i valori concreti che saranno
passati in questa funzione, quindi non sappiamo se il caso if
o il
caso else
sarà eseguito. Non conosciamo nemmeno i lifetimes concreti dei
riferimenti che saranno passati, quindi non possiamo guardare agli ambiti come abbiamo fatto nei
Listings 10-17 e 10-18 per determinare se il riferimento che restituiamo sarà
sempre valido. Neppure il borrow checker può determinarlo, perché non
conosce come i lifetimes di x
e y
si relazionano con il lifetime del
valore restituito. Per risolvere questo errore, aggiungeremo parametri lifetime generici che
definiranno la relazione tra i riferimenti in modo che il borrow checker possa
eseguire la sua analisi.
Sintassi delle Annotazioni dei Lifetimes
Le annotazioni dei lifetimes non cambiano quanto a lungo nessuno dei riferimenti vive. Piuttosto, descrivono le relazioni dei lifetimes di più riferimenti tra loro senza influenzare i lifetimes. Proprio come le funzioni possono accettare qualsiasi tipo quando la firma specifica un parametro tipo generico, le funzioni possono accettare riferimenti con qualsiasi lifetime specificando un parametro lifetime generico.
Le annotazioni dei lifetimes hanno una sintassi leggermente insolita: i nomi dei parametri
lifetime devono iniziare con un apostrofo ('
) e solitamente sono tutti in minuscolo
e molto brevi, come i tipi generici. La maggior parte delle persone utilizza il nome 'a
per la prima annotazione di lifetime. Mettiamo le annotazioni del parametro lifetime dopo il &
di un
riferimento, utilizzando uno spazio per separare l'annotazione dal tipo del riferimento.
Ecco alcuni esempi: un riferimento a un i32
senza un parametro lifetime, un
riferimento a un i32
che ha un parametro lifetime chiamato 'a
, e un riferimento
mutabile a un i32
che ha anche il lifetime 'a
.
&i32 // un riferimento
&'a i32 // un riferimento con un lifetime esplicito
&'a mut i32 // un riferimento mutabile con un lifetime esplicito
Un'annotazione di lifetime da sola non ha molto significato perché le
annotazioni sono destinate a dire a Rust come i parametri lifetime generici di più
riferimenti si relazionano tra loro. Esaminiamo come le annotazioni di lifetime
si relazionano tra loro nel contesto della funzione longest
.
Annotazioni dei Lifetimes nelle Signature delle Funzioni
Per utilizzare le annotazioni dei lifetimes nelle signature delle funzioni, dobbiamo dichiarare i parametri generici lifetime all'interno delle parentesi angolari tra il nome della funzione e l'elenco dei parametri, proprio come abbiamo fatto con i parametri generici tipo.
Vogliamo che la firma esprima il seguente vincolo: il riferimento restituito sarà
valido fintanto che entrambi i parametri sono validi. Questa è la
relazione tra i lifetimes dei parametri e il valore di ritorno.
Nomineremo il lifetime 'a
e poi lo aggiungeremo a ciascun riferimento, come mostrato nel Listing
10-21.
File: src/main.rs
fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }
Questo codice dovrebbe compilare e produrre il risultato desiderato quando lo usiamo con la
funzione main
nel Listing 10-19.
La signature della funzione ora dice a Rust che per un qualche lifetime 'a
, la funzione
prende due parametri, entrambi dei quali sono stringhe slices che vivono almeno tanto quanto
il lifetime 'a
. La signature della funzione dice anche a Rust che la stringa
slice restituita dalla funzione vivrà almeno tanto quanto il lifetime 'a
.
In pratica, significa che il lifetime del riferimento restituito dalla
funzione longest
è lo stesso del minore tra i lifetimes dei valori riferiti dai
parametri della funzione. Queste relazioni sono quelle che vogliamo
che Rust utilizzi quando analizza questo codice.
Ricorda, quando specifichiamo i parametri lifetime in questa signatura di funzione,
non stiamo cambiando i lifetimes di nessun valore passato o restituito. Piuttosto,
stiamo specificando che il borrow checker dovrebbe rigettare qualsiasi valore che non
aderisce a questi vincoli. Nota che la funzione longest
non ha bisogno di
sapere esattamente quanto a lungo x
e y
vivranno, solo che qualche ambito
può essere sostituito per 'a
che soddisferà questa signatura.
Quando annotiamo i lifetimes nelle funzioni, le annotazioni vanno nella signatura della funzione, non nel corpo della funzione. Le annotazioni dei lifetimes diventano parte del contratto della funzione, proprio come i tipi nella signatura. Avere le signatura delle funzioni che contengono il contratto lifetime significa che l'analisi che il compilatore Rust fa può essere più semplice. Se c'è un problema con il modo in cui una funzione è annotata o il modo in cui viene chiamata, gli errori del compilatore possono puntare con più precisione alla parte del nostro codice che causa i vincoli. Se, invece, il compilatore Rust facesse più inferenze su ciò che intendiamo che fossero le relazioni tra i lifetimes, il compilatore potrebbe essere in grado di puntare solo a un uso del nostro codice molti passaggi lontano dalla causa del problema.
Quando passiamo riferimenti concreti a longest
, il lifetime concreto che viene
sostituito per 'a
è la parte dell'ambito di x
che si sovrappone con l'ambito di y
.
In altre parole, il generic lifetime 'a
avrà il lifetime concreto che è uguale al
minore dei lifetimes di x
e y
. Poiché abbiamo annotato il riferimento restituito con
lo stesso parametro lifetime 'a
, il riferimento restituito sarà anche valido per la
durata del minore dei lifetimes di x
e y
.
Vediamo come le annotazioni di lifetime limitano la funzione longest
passando
riferimenti che hanno diversi lifetimes concreti. Il Listing 10-22 è un esempio
semplice.
File: src/main.rs
fn main() { let string1 = String::from("long string is long"); { let string2 = String::from("xyz"); let result = longest(string1.as_str(), string2.as_str()); println!("The longest string is {}", result); } } fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }
In questo esempio, string1
è valido fino alla fine dell'ambito esterno, string2
è valido fino alla fine dell'ambito interno, e result
fa riferimento a qualcosa che
è valido fino alla fine dell'ambito interno. Esegui questo codice e vedrai
che il borrow checker approva; compilerà e stamperà The longest string is long string is long
.
Successivamente, proviamo un esempio che mostra che il lifetime del riferimento in
result
deve essere il minore dei due lifetimes degli argomenti. Sposteremo la
dichiarazione della variabile result
fuori dall'ambito interno, ma lasceremo
l'assegnazione del valore alla variabile result
all'interno dell'ambito con
string2
. Poi sposteremo il println!
che usa result
fuori
dall'ambito interno, dopo che l'ambito interno è terminato. Il codice nel Listing 10-23
non compilerà.
File: src/main.rs
fn main() {
let string1 = String::from("long string is long");
let result;
{
let string2 = String::from("xyz");
result = longest(string1.as_str(), string2.as_str());
}
println!("The longest string is {}", result);
}
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
Quando proviamo a compilare questo codice, otteniamo questo errore:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0597]: `string2` does not live long enough
--> src/main.rs:6:44
|
6 | result = longest(string1.as_str(), string2.as_str());
| ^^^^^^^^^^^^^^^^ borrowed value does not live long enough
7 | }
| - `string2` dropped here while still borrowed
8 | println!("The longest string is {}", result);
| ------ borrow later used here
For more information about this error, try `rustc --explain E0597`.
error: could not compile `chapter10` due to previous error
L'errore mostra che per result
essere valido per l'istruzione println!
,
string2
dovrebbe essere valido fino alla fine dell'ambito esterno. Rust lo
sa perché abbiamo annotato i lifetimes dei parametri della funzione e dei valori di ritorno
utilizzando lo stesso parametro lifetime 'a
.
Come esseri umani, possiamo guardare questo codice e vedere che string1
è più lunga di
string2
, quindi result
conterrà un riferimento a string1
.
Poiché string1
non è ancora uscito dall'ambito, un riferimento a string1
sarà
ancora valido per l'istruzione println!
. Tuttavia, il compilatore non può vedere
che il riferimento è valido in questo caso. Abbiamo detto a Rust che il lifetime del
riferimento restituito dalla funzione longest
è lo stesso del minore dei
lifetimes dei riferimenti passati. Pertanto, il borrow checker
disapprova il codicenel Listing 10-23 come potenzialmente contenente un riferimento non valido.
Prova a progettare ulteriori esperimenti che variano i valori e i lifetimes dei
riferimenti passati alla funzione longest
e come viene utilizzato il riferimento
restituito. Fai ipotesi sul fatto che i tuoi esperimenti supereranno il borrow checker
prima di compilare; poi controlla se hai ragione!
Pensare in Termini di Lifetimes
Il modo in cui devi specificare i parametri lifetime dipende da ciò che
la tua funzione sta facendo. Ad esempio, se modifichiamo l'implementazione della
funzione longest
per restituire sempre il primo parametro anziché la stringa slice più lunga,
non avremmo bisogno di specificare un lifetime sul parametro y
. Il seguente
codice compilerà:
File: src/main.rs
fn main() { let string1 = String::from("abcd"); let string2 = "efghijklmnopqrstuvwxyz"; let result = longest(string1.as_str(), string2); println!("The longest string is {}", result); } fn longest<'a>(x: &'a str, y: &str) -> &'a str { x }
Abbiamo specificato un parametro lifetime 'a
per il parametro x
e per il tipo di ritorno, ma non per il parametro y
, perché il lifetime di y
non ha alcuna relazione con il lifetime di x
o con il valore di ritorno.
Quando si restituisce un riferimento da una funzione, il parametro lifetime per il tipo di ritorno deve corrispondere al parametro lifetime di uno dei parametri. Se il riferimento restituito non si riferisce a uno dei parametri, deve riferirsi a un valore creato all'interno di questa funzione. Tuttavia, questo sarebbe un riferimento dangling (pendente) perché il valore uscirà dallo scope alla fine della funzione. Considera questa implementazione tentata della funzione longest
che non compilerà:
Nome del file: src/main.rs
fn main() {
let string1 = String::from("abcd");
let string2 = "xyz";
let result = longest(string1.as_str(), string2);
println!("The longest string is {}", result);
}
fn longest<'a>(x: &str, y: &str) -> &'a str {
let result = String::from("really long string");
result.as_str()
}
Qui, anche se abbiamo specificato un parametro lifetime 'a
per il tipo di ritorno, questa implementazione non compilerà perché il lifetime del valore di ritorno non è affatto correlato al lifetime dei parametri. Ecco il messaggio di errore che otteniamo:
$ cargo run
Compiling chapter10 v0.1.0 (file:///projects/chapter10)
error[E0515]: cannot return reference to local variable `result`
--> src/main.rs:11:5
|
11 | result.as_str()
| ^^^^^^^^^^^^^^^ returns a reference to data owned by the current function
For more information about this error, try `rustc --explain E0515`.
error: could not compile `chapter10` due to previous error
Il problema è che result
esce dallo scope e viene pulito alla fine della funzione longest
. Stiamo inoltre cercando di restituire un riferimento a result
dalla funzione. Non c'è modo di specificare parametri lifetime che cambierebbero il riferimento dangling, e Rust non ci permetterà di creare un riferimento dangling. In questo caso, la migliore correzione sarebbe restituire un tipo di dato posseduto piuttosto che un riferimento, in modo che la funzione chiamante sia poi responsabile della pulizia del valore.
In definitiva, la sintassi dei lifetime riguarda connettere i lifetime dei vari parametri e valori di ritorno delle funzioni. Una volta connessi, Rust ha abbastanza informazioni per consentire operazioni sicure in memoria e disabilitare operazioni che creerebbero puntatori dangling o violerebbero in altro modo la sicurezza della memoria.
Annotazioni di Lifetime nelle Definizioni delle Struct
Finora, le struct che abbiamo definito contengono tutti tipi posseduti. Possiamo definire struct per contenere riferimenti, ma in tal caso dovremmo aggiungere un'annotazione di lifetime su ogni riferimento nella definizione della struct. Listing 10-24 contiene una struct chiamata ImportantExcerpt
che contiene una string slice.
Nome del file: src/main.rs
struct ImportantExcerpt<'a> { part: &'a str, } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; }
Questa struct ha il campo unico part
che contiene una string slice, che è un riferimento. Come con i tipi di dati generici, dichiariamo il nome del parametro lifetime generico tra parentesi angolari dopo il nome della struct in modo da poter usare il parametro lifetime nel corpo della definizione della struct. Questa annotazione significa che un'istanza di ImportantExcerpt
non può vivere più a lungo del riferimento che contiene nel campo part
.
La funzione main
qui crea un'istanza della struct ImportantExcerpt
che contiene un riferimento alla prima frase del String
posseduto dalla variabile novel
. I dati in novel
esistono prima della creazione dell'istanza di ImportantExcerpt
. Inoltre, novel
non esce dallo scope fino a quando anche ImportantExcerpt
non esce dallo scope, quindi il riferimento nell'istanza di ImportantExcerpt
è valido.
Omissione del Lifetime
Hai appreso che ogni riferimento ha un lifetime e che devi specificare parametri lifetime per funzioni o struct che usano riferimenti. Tuttavia, avevamo una funzione nel Listing 4-9, mostrata di nuovo nel Listing 10-25, che compilava senza annotazioni di lifetime.
Nome del file: src/lib.rs
fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // first_word works on slices of `String`s let word = first_word(&my_string[..]); let my_string_literal = "hello world"; // first_word works on slices of string literals let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); }
Il motivo per cui questa funzione compila senza annotazioni di lifetime è storico: nelle prime versioni (pre-1.0) di Rust, questo codice non avrebbe compilato perché ogni riferimento necessitava di un lifetime esplicito. A quel tempo, la firma della funzione sarebbe stata scritta così:
fn first_word<'a>(s: &'a str) -> &'a str {
Dopo aver scritto molto codice Rust, il team di Rust ha scoperto che i programmatori Rust inserivano ripetutamente le stesse annotazioni di lifetime in particolari situazioni. Queste situazioni erano prevedibili e seguivano alcuni schemi deterministici. Gli sviluppatori hanno programmato questi schemi nel codice del compilatore in modo che il borrow checker potesse inferire i lifetime in queste situazioni e non avrebbe bisogno di annotazioni esplicite.
Questo pezzo di storia di Rust è rilevante perché è possibile che emergano più schemi deterministici e vengano aggiunti al compilatore. In futuro, potrebbero essere richieste ancora meno annotazioni di lifetime.
Gli schemi programmati nell'analisi dei riferimenti di Rust sono chiamati regole di omissione del lifetime. Queste non sono regole che i programmatori devono seguire; sono un insieme di casi particolari che il compilatore considererà, e se il tuo codice si adatta a questi casi, non devi scrivere esplicitamente i lifetime.
Le regole di omissione non forniscono un'inferenza completa. Se l’ambiguità rimane riguardo ai lifetime dei riferimenti dopo che Rust ha applicato le regole, il compilatore non indovinerà quale debba essere il lifetime dei riferimenti rimanenti. Invece di indovinare, il compilatore ti darà un errore che puoi risolvere aggiungendo le annotazioni di lifetime.
I lifetime sui parametri delle funzioni o dei metodi sono chiamati input lifetimes, e i lifetime sui valori di ritorno sono chiamati output lifetimes.
Il compilatore utilizza tre regole per determinare i lifetime dei riferimenti quando non ci sono annotazioni esplicite. La prima regola si applica ai lifetime di input, e la seconda e terza regola si applicano agli output lifetimes. Se il compilatore arriva alla fine delle tre regole e ci sono ancora riferimenti per i quali non può determinare i lifetime, il compilatore si interromperà con un errore. Queste regole si applicano sia alle definizioni fn
che ai blocchi impl
.
La prima regola è che il compilatore assegna un parametro lifetime a ciascun parametro che è un riferimento. In altre parole, una funzione con un parametro ottiene un parametro lifetime: fn foo<'a>(x: &'a i32)
; una funzione con due parametri ottiene due parametri lifetime separati: fn foo<'a, 'b>(x: &'a i32, y: &'b i32)
; e così via.
La seconda regola è che, se c’è esattamente un parametro di input lifetime, quel lifetime viene assegnato a tutti i parametri output lifetime: fn foo<'a>(x: &'a i32) -> &'a i32
.
La terza regola è che, se ci sono più parametri di input lifetime, ma uno di questi è &self
o &mut self
perché questo è un metodo, il lifetime di self
viene assegnato a tutti i parametri output lifetime. Questa terza regola rende molto più leggibili e scrivibili i metodi perché sono necessari meno simboli.
Facciamo finta di essere il compilatore. Applicheremo queste regole per determinare i lifetime dei riferimenti nella firma della funzione first_word
nel Listing 10-25. La firma inizia senza lifetime associati ai riferimenti:
fn first_word(s: &str) -> &str {
Poi il compilatore applica la prima regola, che specifica che ogni parametro ottiene il proprio lifetime. Lo chiameremo 'a
come al solito, quindi ora la firma è questa:
fn first_word<'a>(s: &'a str) -> &str {
La seconda regola si applica perché c’è esattamente un parametro di input lifetime. La seconda regola specifica che il lifetime dell’unico parametro di input viene assegnato all'output lifetime, quindi la firma è ora questa:
fn first_word<'a>(s: &'a str) -> &'a str {
Ora tutti i riferimenti in questa firma di funzione hanno lifetime, e il compilatore può continuare la sua analisi senza bisogno che il programmatore annoti i lifetime in questa firma di funzione.
Guardiamo un altro esempio, questa volta usando la funzione longest
che non aveva parametri lifetime quando abbiamo iniziato a lavorare con essa nel Listing 10-20:
fn longest(x: &str, y: &str) -> &str {
Applichiamo la prima regola: ogni parametro ottiene il proprio lifetime. Stavolta abbiamo due parametri invece di uno, quindi abbiamo due lifetime:
fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {
Puoi vedere che la seconda regola non si applica perché ci sono più di un lifetime di input. La terza regola non si applica nemmeno, perché longest
è una funzione piuttosto che un metodo, quindi nessuno dei parametri è self
. Dopo aver esaminato tutte e tre le regole, non abbiamo ancora determinato quale sia il lifetime del tipo di ritorno. Questo è il motivo per cui abbiamo avuto un errore tentando di compilare il codice nel Listing 10-20: il compilatore ha applicato le regole di omissione del lifetime ma non è riuscito a determinare tutti i lifetime dei riferimenti nella firma.
Poiché la terza regola si applica realmente solo alle firme dei metodi, esamineremo i lifetime in quel contesto successivamente per vedere perché la terza regola significa che non dobbiamo spesso annotare i lifetime nelle firme dei metodi.
Annotazioni di Lifetime nelle Definizioni dei Metodi
Quando implementiamo metodi su una struct con dei lifetime, usiamo la stessa sintassi dei parametri di tipo generico mostrati nel Listing 10-11. Dove dichiariamo e utilizziamo i parametri lifetime dipende dal fatto che siano correlati ai campi della struct o ai parametri e valori di ritorno del metodo.
I nomi dei lifetime per i campi delle struct devono sempre essere dichiarati dopo la parola chiave impl
e poi utilizzati dopo il nome della struct perché quei lifetime fanno parte del tipo della struct.
Nelle firme dei metodi all'interno del blocco impl
, i riferimenti potrebbero essere legati al lifetime dei riferimenti nei campi della struct, oppure potrebbero essere indipendenti. Inoltre, le regole di omissione del lifetime spesso fanno sì che le annotazioni di lifetime non siano necessarie nelle firme dei metodi. Esaminiamo alcuni esempi usando la struct chiamata ImportantExcerpt
che abbiamo definito nel Listing 10-24.
Per prima cosa useremo un metodo chiamato level
il cui unico parametro è un riferimento a self
e il cui valore di ritorno è un i32
, che non è un riferimento a nulla:
struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 3 } } impl<'a> ImportantExcerpt<'a> { fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Attention please: {}", announcement); self.part } } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; }
La dichiarazione del parametro lifetime dopo impl
e il suo uso dopo il nome del tipo sono richiesti, ma non siamo obbligati ad annotare il lifetime del riferimento a self
a causa della prima regola di omissione.
Ecco un esempio in cui si applica la terza regola di omissione del lifetime:
struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 3 } } impl<'a> ImportantExcerpt<'a> { fn announce_and_return_part(&self, announcement: &str) -> &str { println!("Attention please: {}", announcement); self.part } } fn main() { let novel = String::from("Call me Ishmael. Some years ago..."); let first_sentence = novel.split('.').next().expect("Could not find a '.'"); let i = ImportantExcerpt { part: first_sentence, }; }
Ci sono due lifetime di input, quindi Rust applica la prima regola di omissione del lifetime e assegna a entrambe &self
e announcement
i loro lifetime. Poi, poiché uno dei parametri è &self
, il tipo di ritorno ottiene il lifetime di &self
, e tutti i lifetime sono stati contabilizzati.
Il Lifetime Statico
Un lifetime speciale di cui dobbiamo discutere è 'static
, che indica che il riferimento interessato può vivere per l'intera durata del programma. Tutti i letterali di stringa hanno il lifetime 'static
, che possiamo annotare come segue:
#![allow(unused)] fn main() { let s: &'static str = "I have a static lifetime."; }
Il testo di questa stringa è memorizzato direttamente nel binario del programma, che è sempre disponibile. Pertanto, il lifetime di tutti i letterali di stringa è 'static
.
Potresti vedere suggerimenti per usare il lifetime 'static
nei messaggi di errore. Ma prima di specificare 'static
come lifetime per un riferimento, pensa se il riferimento che hai effettivamente vive per l'intera durata del tuo programma o no, e se lo vuoi. La maggior parte delle volte, un messaggio di errore che suggerisce il lifetime 'static
risulta dal tentativo di creare un riferimento pendente o un mismatch dei lifetime disponibili. In tali casi, la soluzione è risolvere questi problemi, non specificare il lifetime 'static
.
Parametri di Tipo Generico, Trait Bounds, e Lifetimes Insieme
Diamo una breve occhiata alla sintassi di specificare parametri di tipo generico, trait bounds e lifetimes tutti in una funzione!
fn main() { let string1 = String::from("abcd"); let string2 = "xyz"; let result = longest_with_an_announcement( string1.as_str(), string2, "Today is someone's birthday!", ); println!("The longest string is {}", result); } use std::fmt::Display; fn longest_with_an_announcement<'a, T>( x: &'a str, y: &'a str, ann: T, ) -> &'a str where T: Display, { println!("Announcement! {}", ann); if x.len() > y.len() { x } else { y } }
Questa è la funzione longest
del Listing 10-21 che restituisce la slice di stringa più lunga. Ma ora ha un parametro extra chiamato ann
del tipo generico T
, che può essere riempito da qualsiasi tipo che implementa il trait Display
come specificato dalla clausola where
. Questo parametro extra sarà stampato usando {}
, motivo per cui il trait bound Display
è necessario. Poiché i lifetime sono un tipo di generico, le dichiarazioni del parametro lifetime 'a
e del parametro di tipo generico T
vanno nella stessa lista all'interno delle parentesi angolari dopo il nome della funzione.
Riepilogo
Abbiamo coperto molto in questo capitolo! Ora che sai sui parametri di tipo generico, trait e trait bounds, e parametri di lifetime generici, sei pronto a scrivere codice senza ripetizioni che funziona in molte situazioni diverse. I parametri di tipo generico ti permettono di applicare il codice a tipi differenti. I trait e trait bounds assicurano che anche se i tipi sono generici, avranno il comportamento che il codice richiede. Hai imparato come utilizzare le annotazioni di lifetime per assicurarti che questo codice flessibile non avrà riferimenti pendenti. E tutta questa analisi avviene in fase di compilazione, il che non influisce sulle prestazioni runtime!
Credici o no, c'è molto di più da imparare sugli argomenti discussi in questo capitolo: il Capitolo 17 discute degli oggetti trait, che sono un altro modo per usare i trait. Ci sono anche scenari più complessi che coinvolgono annotazioni di lifetime che avrai bisogno solo in scenari molto avanzati; per quelli, dovresti leggere il Riferimento Rust. Ma ora, imparerai come scrivere test in Rust in modo da poter assicurarti che il tuo codice funzioni come dovrebbe.
Writing Automated Tests
In his 1972 essay “The Humble Programmer,” Edsger W. Dijkstra said that “Program testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.” That doesn’t mean we shouldn’t try to test as much as we can!
Correctness in our programs is the extent to which our code does what we intend it to do. Rust is designed with a high degree of concern about the correctness of programs, but correctness is complex and not easy to prove. Rust’s type system shoulders a huge part of this burden, but the type system cannot catch everything. As such, Rust includes support for writing automated software tests.
Say we write a function add_two
that adds 2 to whatever number is passed to
it. This function’s signature accepts an integer as a parameter and returns an
integer as a result. When we implement and compile that function, Rust does all
the type checking and borrow checking that you’ve learned so far to ensure
that, for instance, we aren’t passing a String
value or an invalid reference
to this function. But Rust can’t check that this function will do precisely
what we intend, which is return the parameter plus 2 rather than, say, the
parameter plus 10 or the parameter minus 50! That’s where tests come in.
We can write tests that assert, for example, that when we pass 3
to the
add_two
function, the returned value is 5
. We can run these tests whenever
we make changes to our code to make sure any existing correct behavior has not
changed.
Testing is a complex skill: although we can’t cover every detail about how to write good tests in one chapter, we’ll discuss the mechanics of Rust’s testing facilities. We’ll talk about the annotations and macros available to you when writing your tests, the default behavior and options provided for running your tests, and how to organize tests into unit tests and integration tests.
How to Write Tests
Tests are Rust functions that verify that the non-test code is functioning in the expected manner. The bodies of test functions typically perform these three actions:
- Set up any needed data or state.
- Run the code you want to test.
- Assert the results are what you expect.
Let’s look at the features Rust provides specifically for writing tests that
take these actions, which include the test
attribute, a few macros, and the
should_panic
attribute.
The Anatomy of a Test Function
At its simplest, a test in Rust is a function that’s annotated with the test
attribute. Attributes are metadata about pieces of Rust code; one example is
the derive
attribute we used with structs in Chapter 5. To change a function
into a test function, add #[test]
on the line before fn
. When you run your
tests with the cargo test
command, Rust builds a test runner binary that runs
the annotated functions and reports on whether each
test function passes or fails.
Whenever we make a new library project with Cargo, a test module with a test function in it is automatically generated for us. This module gives you a template for writing your tests so you don’t have to look up the exact structure and syntax every time you start a new project. You can add as many additional test functions and as many test modules as you want!
We’ll explore some aspects of how tests work by experimenting with the template test before we actually test any code. Then we’ll write some real-world tests that call some code that we’ve written and assert that its behavior is correct.
Let’s create a new library project called adder
that will add two numbers:
$ cargo new adder --lib
Created library `adder` project
$ cd adder
The contents of the src/lib.rs file in your adder
library should look like
Listing 11-1.
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}
For now, let’s ignore the top two lines and focus on the function. Note the
#[test]
annotation: this attribute indicates this is a test function, so the
test runner knows to treat this function as a test. We might also have non-test
functions in the tests
module to help set up common scenarios or perform
common operations, so we always need to indicate which functions are tests.
The example function body uses the assert_eq!
macro to assert that result
,
which contains the result of adding 2 and 2, equals 4. This assertion serves as
an example of the format for a typical test. Let’s run it to see that this test
passes.
The cargo test
command runs all tests in our project, as shown in Listing
11-2.
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.57s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Cargo compiled and ran the test. We see the line running 1 test
. The next
line shows the name of the generated test function, called it_works
, and that
the result of running that test is ok
. The overall summary test result: ok.
means that all the tests passed, and the portion that reads 1 passed; 0 failed
totals the number of tests that passed or failed.
It’s possible to mark a test as ignored so it doesn’t run in a particular
instance; we’ll cover that in the “Ignoring Some Tests Unless Specifically
Requested” section later in this chapter. Because we
haven’t done that here, the summary shows 0 ignored
. We can also pass an
argument to the cargo test
command to run only tests whose name matches a
string; this is called filtering and we’ll cover that in the “Running a
Subset of Tests by Name” section. We also haven’t
filtered the tests being run, so the end of the summary shows 0 filtered out
.
The 0 measured
statistic is for benchmark tests that measure performance.
Benchmark tests are, as of this writing, only available in nightly Rust. See
the documentation about benchmark tests to learn more.
The next part of the test output starting at Doc-tests adder
is for the
results of any documentation tests. We don’t have any documentation tests yet,
but Rust can compile any code examples that appear in our API documentation.
This feature helps keep your docs and your code in sync! We’ll discuss how to
write documentation tests in the “Documentation Comments as
Tests” section of Chapter 14. For now, we’ll
ignore the Doc-tests
output.
Let’s start to customize the test to our own needs. First change the name of
the it_works
function to a different name, such as exploration
, like so:
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn exploration() {
assert_eq!(2 + 2, 4);
}
}
Then run cargo test
again. The output now shows exploration
instead of
it_works
:
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.59s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::exploration ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Now we’ll add another test, but this time we’ll make a test that fails! Tests
fail when something in the test function panics. Each test is run in a new
thread, and when the main thread sees that a test thread has died, the test is
marked as failed. In Chapter 9, we talked about how the simplest way to panic
is to call the panic!
macro. Enter the new test as a function named
another
, so your src/lib.rs file looks like Listing 11-3.
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn exploration() {
assert_eq!(2 + 2, 4);
}
#[test]
fn another() {
panic!("Make this test fail");
}
}
Run the tests again using cargo test
. The output should look like Listing
11-4, which shows that our exploration
test passed and another
failed.
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.72s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests
test tests::another ... FAILED
test tests::exploration ... ok
failures:
---- tests::another stdout ----
thread 'tests::another' panicked at 'Make this test fail', src/lib.rs:10:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::another
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Instead of ok
, the line test tests::another
shows FAILED
. Two new
sections appear between the individual results and the summary: the first
displays the detailed reason for each test failure. In this case, we get the
details that another
failed because it panicked at 'Make this test fail'
on
line 10 in the src/lib.rs file. The next section lists just the names of all
the failing tests, which is useful when there are lots of tests and lots of
detailed failing test output. We can use the name of a failing test to run just
that test to more easily debug it; we’ll talk more about ways to run tests in
the “Controlling How Tests Are Run” section.
The summary line displays at the end: overall, our test result is FAILED
. We
had one test pass and one test fail.
Now that you’ve seen what the test results look like in different scenarios,
let’s look at some macros other than panic!
that are useful in tests.
Checking Results with the assert!
Macro
The assert!
macro, provided by the standard library, is useful when you want
to ensure that some condition in a test evaluates to true
. We give the
assert!
macro an argument that evaluates to a Boolean. If the value is
true
, nothing happens and the test passes. If the value is false
, the
assert!
macro calls panic!
to cause the test to fail. Using the assert!
macro helps us check that our code is functioning in the way we intend.
In Chapter 5, Listing 5-15, we used a Rectangle
struct and a can_hold
method, which are repeated here in Listing 11-5. Let’s put this code in the
src/lib.rs file, then write some tests for it using the assert!
macro.
Filename: src/lib.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
The can_hold
method returns a Boolean, which means it’s a perfect use case
for the assert!
macro. In Listing 11-6, we write a test that exercises the
can_hold
method by creating a Rectangle
instance that has a width of 8 and
a height of 7 and asserting that it can hold another Rectangle
instance that
has a width of 5 and a height of 1.
Filename: src/lib.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(larger.can_hold(&smaller));
}
}
Note that we’ve added a new line inside the tests
module: use super::*;
.
The tests
module is a regular module that follows the usual visibility rules
we covered in Chapter 7 in the “Paths for Referring to an Item in the Module
Tree”
section. Because the tests
module is an inner module, we need to bring the
code under test in the outer module into the scope of the inner module. We use
a glob here so anything we define in the outer module is available to this
tests
module.
We’ve named our test larger_can_hold_smaller
, and we’ve created the two
Rectangle
instances that we need. Then we called the assert!
macro and
passed it the result of calling larger.can_hold(&smaller)
. This expression is
supposed to return true
, so our test should pass. Let’s find out!
$ cargo test
Compiling rectangle v0.1.0 (file:///projects/rectangle)
Finished test [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)
running 1 test
test tests::larger_can_hold_smaller ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests rectangle
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
It does pass! Let’s add another test, this time asserting that a smaller rectangle cannot hold a larger rectangle:
Filename: src/lib.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
// --snip--
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(larger.can_hold(&smaller));
}
#[test]
fn smaller_cannot_hold_larger() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(!smaller.can_hold(&larger));
}
}
Because the correct result of the can_hold
function in this case is false
,
we need to negate that result before we pass it to the assert!
macro. As a
result, our test will pass if can_hold
returns false
:
$ cargo test
Compiling rectangle v0.1.0 (file:///projects/rectangle)
Finished test [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)
running 2 tests
test tests::larger_can_hold_smaller ... ok
test tests::smaller_cannot_hold_larger ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests rectangle
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Two tests that pass! Now let’s see what happens to our test results when we
introduce a bug in our code. We’ll change the implementation of the can_hold
method by replacing the greater-than sign with a less-than sign when it
compares the widths:
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
// --snip--
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width < other.width && self.height > other.height
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn larger_can_hold_smaller() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(larger.can_hold(&smaller));
}
#[test]
fn smaller_cannot_hold_larger() {
let larger = Rectangle {
width: 8,
height: 7,
};
let smaller = Rectangle {
width: 5,
height: 1,
};
assert!(!smaller.can_hold(&larger));
}
}
Running the tests now produces the following:
$ cargo test
Compiling rectangle v0.1.0 (file:///projects/rectangle)
Finished test [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/rectangle-6584c4561e48942e)
running 2 tests
test tests::larger_can_hold_smaller ... FAILED
test tests::smaller_cannot_hold_larger ... ok
failures:
---- tests::larger_can_hold_smaller stdout ----
thread 'tests::larger_can_hold_smaller' panicked at 'assertion failed: larger.can_hold(&smaller)', src/lib.rs:28:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::larger_can_hold_smaller
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Our tests caught the bug! Because larger.width
is 8 and smaller.width
is
5, the comparison of the widths in can_hold
now returns false
: 8 is not
less than 5.
Testing Equality with the assert_eq!
and assert_ne!
Macros
A common way to verify functionality is to test for equality between the result
of the code under test and the value you expect the code to return. You could
do this using the assert!
macro and passing it an expression using the ==
operator. However, this is such a common test that the standard library
provides a pair of macros—assert_eq!
and assert_ne!
—to perform this test
more conveniently. These macros compare two arguments for equality or
inequality, respectively. They’ll also print the two values if the assertion
fails, which makes it easier to see why the test failed; conversely, the
assert!
macro only indicates that it got a false
value for the ==
expression, without printing the values that led to the false
value.
In Listing 11-7, we write a function named add_two
that adds 2
to its
parameter, then we test this function using the assert_eq!
macro.
Filename: src/lib.rs
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds_two() {
assert_eq!(4, add_two(2));
}
}
Let’s check that it passes!
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
We pass 4
as the argument to assert_eq!
, which is equal to the result of
calling add_two(2)
. The line for this test is test tests::it_adds_two ... ok
, and the ok
text indicates that our test passed!
Let’s introduce a bug into our code to see what assert_eq!
looks like when it
fails. Change the implementation of the add_two
function to instead add 3
:
pub fn add_two(a: i32) -> i32 {
a + 3
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds_two() {
assert_eq!(4, add_two(2));
}
}
Run the tests again:
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.61s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::it_adds_two ... FAILED
failures:
---- tests::it_adds_two stdout ----
thread 'tests::it_adds_two' panicked at 'assertion failed: `(left == right)`
left: `4`,
right: `5`', src/lib.rs:11:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::it_adds_two
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Our test caught the bug! The it_adds_two
test failed, and the message tells
us that the assertion that fails was assertion failed: `(left == right)`
and what the left
and right
values are. This message helps us start
debugging: the left
argument was 4
but the right
argument, where we had
add_two(2)
, was 5
. You can imagine that this would be especially helpful
when we have a lot of tests going on.
Note that in some languages and test frameworks, the parameters to equality
assertion functions are called expected
and actual
, and the order in which
we specify the arguments matters. However, in Rust, they’re called left
and
right
, and the order in which we specify the value we expect and the value
the code produces doesn’t matter. We could write the assertion in this test as
assert_eq!(add_two(2), 4)
, which would result in the same failure message
that displays assertion failed: `(left == right)`
.
The assert_ne!
macro will pass if the two values we give it are not equal and
fail if they’re equal. This macro is most useful for cases when we’re not sure
what a value will be, but we know what the value definitely shouldn’t be.
For example, if we’re testing a function that is guaranteed to change its input
in some way, but the way in which the input is changed depends on the day of
the week that we run our tests, the best thing to assert might be that the
output of the function is not equal to the input.
Under the surface, the assert_eq!
and assert_ne!
macros use the operators
==
and !=
, respectively. When the assertions fail, these macros print their
arguments using debug formatting, which means the values being compared must
implement the PartialEq
and Debug
traits. All primitive types and most of
the standard library types implement these traits. For structs and enums that
you define yourself, you’ll need to implement PartialEq
to assert equality of
those types. You’ll also need to implement Debug
to print the values when the
assertion fails. Because both traits are derivable traits, as mentioned in
Listing 5-12 in Chapter 5, this is usually as straightforward as adding the
#[derive(PartialEq, Debug)]
annotation to your struct or enum definition. See
Appendix C, “Derivable Traits,” for more
details about these and other derivable traits.
Adding Custom Failure Messages
You can also add a custom message to be printed with the failure message as
optional arguments to the assert!
, assert_eq!
, and assert_ne!
macros. Any
arguments specified after the required arguments are passed along to the
format!
macro (discussed in Chapter 8 in the “Concatenation with the +
Operator or the format!
Macro”
section), so you can pass a format string that contains {}
placeholders and
values to go in those placeholders. Custom messages are useful for documenting
what an assertion means; when a test fails, you’ll have a better idea of what
the problem is with the code.
For example, let’s say we have a function that greets people by name and we want to test that the name we pass into the function appears in the output:
Filename: src/lib.rs
pub fn greeting(name: &str) -> String {
format!("Hello {}!", name)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greeting_contains_name() {
let result = greeting("Carol");
assert!(result.contains("Carol"));
}
}
The requirements for this program haven’t been agreed upon yet, and we’re
pretty sure the Hello
text at the beginning of the greeting will change. We
decided we don’t want to have to update the test when the requirements change,
so instead of checking for exact equality to the value returned from the
greeting
function, we’ll just assert that the output contains the text of the
input parameter.
Now let’s introduce a bug into this code by changing greeting
to exclude
name
to see what the default test failure looks like:
pub fn greeting(name: &str) -> String {
String::from("Hello!")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greeting_contains_name() {
let result = greeting("Carol");
assert!(result.contains("Carol"));
}
}
Running this test produces the following:
$ cargo test
Compiling greeter v0.1.0 (file:///projects/greeter)
Finished test [unoptimized + debuginfo] target(s) in 0.91s
Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)
running 1 test
test tests::greeting_contains_name ... FAILED
failures:
---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at 'assertion failed: result.contains(\"Carol\")', src/lib.rs:12:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::greeting_contains_name
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
This result just indicates that the assertion failed and which line the
assertion is on. A more useful failure message would print the value from the
greeting
function. Let’s add a custom failure message composed of a format
string with a placeholder filled in with the actual value we got from the
greeting
function:
pub fn greeting(name: &str) -> String {
String::from("Hello!")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn greeting_contains_name() {
let result = greeting("Carol");
assert!(
result.contains("Carol"),
"Greeting did not contain name, value was `{}`",
result
);
}
}
Now when we run the test, we’ll get a more informative error message:
$ cargo test
Compiling greeter v0.1.0 (file:///projects/greeter)
Finished test [unoptimized + debuginfo] target(s) in 0.93s
Running unittests src/lib.rs (target/debug/deps/greeter-170b942eb5bf5e3a)
running 1 test
test tests::greeting_contains_name ... FAILED
failures:
---- tests::greeting_contains_name stdout ----
thread 'tests::greeting_contains_name' panicked at 'Greeting did not contain name, value was `Hello!`', src/lib.rs:12:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::greeting_contains_name
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
We can see the value we actually got in the test output, which would help us debug what happened instead of what we were expecting to happen.
Checking for Panics with should_panic
In addition to checking return values, it’s important to check that our code
handles error conditions as we expect. For example, consider the Guess
type
that we created in Chapter 9, Listing 9-13. Other code that uses Guess
depends on the guarantee that Guess
instances will contain only values
between 1 and 100. We can write a test that ensures that attempting to create a
Guess
instance with a value outside that range panics.
We do this by adding the attribute should_panic
to our test function. The
test passes if the code inside the function panics; the test fails if the code
inside the function doesn’t panic.
Listing 11-8 shows a test that checks that the error conditions of Guess::new
happen when we expect them to.
Filename: src/lib.rs
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn greater_than_100() {
Guess::new(200);
}
}
We place the #[should_panic]
attribute after the #[test]
attribute and
before the test function it applies to. Let’s look at the result when this test
passes:
$ cargo test
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished test [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)
running 1 test
test tests::greater_than_100 - should panic ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests guessing_game
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Looks good! Now let’s introduce a bug in our code by removing the condition
that the new
function will panic if the value is greater than 100:
pub struct Guess {
value: i32,
}
// --snip--
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn greater_than_100() {
Guess::new(200);
}
}
When we run the test in Listing 11-8, it will fail:
$ cargo test
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished test [unoptimized + debuginfo] target(s) in 0.62s
Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)
running 1 test
test tests::greater_than_100 - should panic ... FAILED
failures:
---- tests::greater_than_100 stdout ----
note: test did not panic as expected
failures:
tests::greater_than_100
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
We don’t get a very helpful message in this case, but when we look at the test
function, we see that it’s annotated with #[should_panic]
. The failure we got
means that the code in the test function did not cause a panic.
Tests that use should_panic
can be imprecise. A should_panic
test would
pass even if the test panics for a different reason from the one we were
expecting. To make should_panic
tests more precise, we can add an optional
expected
parameter to the should_panic
attribute. The test harness will
make sure that the failure message contains the provided text. For example,
consider the modified code for Guess
in Listing 11-9 where the new
function
panics with different messages depending on whether the value is too small or
too large.
Filename: src/lib.rs
pub struct Guess {
value: i32,
}
// --snip--
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 {
panic!(
"Guess value must be greater than or equal to 1, got {}.",
value
);
} else if value > 100 {
panic!(
"Guess value must be less than or equal to 100, got {}.",
value
);
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "less than or equal to 100")]
fn greater_than_100() {
Guess::new(200);
}
}
This test will pass because the value we put in the should_panic
attribute’s
expected
parameter is a substring of the message that the Guess::new
function panics with. We could have specified the entire panic message that we
expect, which in this case would be Guess value must be less than or equal to 100, got 200.
What you choose to specify depends on how much of the panic
message is unique or dynamic and how precise you want your test to be. In this
case, a substring of the panic message is enough to ensure that the code in the
test function executes the else if value > 100
case.
To see what happens when a should_panic
test with an expected
message
fails, let’s again introduce a bug into our code by swapping the bodies of the
if value < 1
and the else if value > 100
blocks:
pub struct Guess {
value: i32,
}
impl Guess {
pub fn new(value: i32) -> Guess {
if value < 1 {
panic!(
"Guess value must be less than or equal to 100, got {}.",
value
);
} else if value > 100 {
panic!(
"Guess value must be greater than or equal to 1, got {}.",
value
);
}
Guess { value }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic(expected = "less than or equal to 100")]
fn greater_than_100() {
Guess::new(200);
}
}
This time when we run the should_panic
test, it will fail:
$ cargo test
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
Finished test [unoptimized + debuginfo] target(s) in 0.66s
Running unittests src/lib.rs (target/debug/deps/guessing_game-57d70c3acb738f4d)
running 1 test
test tests::greater_than_100 - should panic ... FAILED
failures:
---- tests::greater_than_100 stdout ----
thread 'tests::greater_than_100' panicked at 'Guess value must be greater than or equal to 1, got 200.', src/lib.rs:13:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
note: panic did not contain expected string
panic message: `"Guess value must be greater than or equal to 1, got 200."`,
expected substring: `"less than or equal to 100"`
failures:
tests::greater_than_100
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
The failure message indicates that this test did indeed panic as we expected,
but the panic message did not include the expected string 'Guess value must be less than or equal to 100'
. The panic message that we did get in this case was
Guess value must be greater than or equal to 1, got 200.
Now we can start
figuring out where our bug is!
Using Result<T, E>
in Tests
Our tests so far all panic when they fail. We can also write tests that use
Result<T, E>
! Here’s the test from Listing 11-1, rewritten to use Result<T, E>
and return an Err
instead of panicking:
#[cfg(test)]
mod tests {
#[test]
fn it_works() -> Result<(), String> {
if 2 + 2 == 4 {
Ok(())
} else {
Err(String::from("two plus two does not equal four"))
}
}
}
The it_works
function now has the Result<(), String>
return type. In the
body of the function, rather than calling the assert_eq!
macro, we return
Ok(())
when the test passes and an Err
with a String
inside when the test
fails.
Writing tests so they return a Result<T, E>
enables you to use the question
mark operator in the body of tests, which can be a convenient way to write
tests that should fail if any operation within them returns an Err
variant.
You can’t use the #[should_panic]
annotation on tests that use Result<T, E>
. To assert that an operation returns an Err
variant, don’t use the
question mark operator on the Result<T, E>
value. Instead, use
assert!(value.is_err())
.
Now that you know several ways to write tests, let’s look at what is happening
when we run our tests and explore the different options we can use with cargo test
.
Controlling How Tests Are Run
Just as cargo run
compiles your code and then runs the resulting binary,
cargo test
compiles your code in test mode and runs the resulting test
binary. The default behavior of the binary produced by cargo test
is to run
all the tests in parallel and capture output generated during test runs,
preventing the output from being displayed and making it easier to read the
output related to the test results. You can, however, specify command line
options to change this default behavior.
Some command line options go to cargo test
, and some go to the resulting test
binary. To separate these two types of arguments, you list the arguments that
go to cargo test
followed by the separator --
and then the ones that go to
the test binary. Running cargo test --help
displays the options you can use
with cargo test
, and running cargo test -- --help
displays the options you
can use after the separator.
Running Tests in Parallel or Consecutively
When you run multiple tests, by default they run in parallel using threads, meaning they finish running faster and you get feedback quicker. Because the tests are running at the same time, you must make sure your tests don’t depend on each other or on any shared state, including a shared environment, such as the current working directory or environment variables.
For example, say each of your tests runs some code that creates a file on disk named test-output.txt and writes some data to that file. Then each test reads the data in that file and asserts that the file contains a particular value, which is different in each test. Because the tests run at the same time, one test might overwrite the file in the time between another test writing and reading the file. The second test will then fail, not because the code is incorrect but because the tests have interfered with each other while running in parallel. One solution is to make sure each test writes to a different file; another solution is to run the tests one at a time.
If you don’t want to run the tests in parallel or if you want more fine-grained
control over the number of threads used, you can send the --test-threads
flag
and the number of threads you want to use to the test binary. Take a look at
the following example:
$ cargo test -- --test-threads=1
We set the number of test threads to 1
, telling the program not to use any
parallelism. Running the tests using one thread will take longer than running
them in parallel, but the tests won’t interfere with each other if they share
state.
Showing Function Output
By default, if a test passes, Rust’s test library captures anything printed to
standard output. For example, if we call println!
in a test and the test
passes, we won’t see the println!
output in the terminal; we’ll see only the
line that indicates the test passed. If a test fails, we’ll see whatever was
printed to standard output with the rest of the failure message.
As an example, Listing 11-10 has a silly function that prints the value of its parameter and returns 10, as well as a test that passes and a test that fails.
Filename: src/lib.rs
fn prints_and_returns_10(a: i32) -> i32 {
println!("I got the value {}", a);
10
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn this_test_will_pass() {
let value = prints_and_returns_10(4);
assert_eq!(10, value);
}
#[test]
fn this_test_will_fail() {
let value = prints_and_returns_10(8);
assert_eq!(5, value);
}
}
When we run these tests with cargo test
, we’ll see the following output:
$ cargo test
Compiling silly-function v0.1.0 (file:///projects/silly-function)
Finished test [unoptimized + debuginfo] target(s) in 0.58s
Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)
running 2 tests
test tests::this_test_will_fail ... FAILED
test tests::this_test_will_pass ... ok
failures:
---- tests::this_test_will_fail stdout ----
I got the value 8
thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)`
left: `5`,
right: `10`', src/lib.rs:19:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::this_test_will_fail
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Note that nowhere in this output do we see I got the value 4
, which is what
is printed when the test that passes runs. That output has been captured. The
output from the test that failed, I got the value 8
, appears in the section
of the test summary output, which also shows the cause of the test failure.
If we want to see printed values for passing tests as well, we can tell Rust
to also show the output of successful tests with --show-output
.
$ cargo test -- --show-output
When we run the tests in Listing 11-10 again with the --show-output
flag, we
see the following output:
$ cargo test -- --show-output
Compiling silly-function v0.1.0 (file:///projects/silly-function)
Finished test [unoptimized + debuginfo] target(s) in 0.60s
Running unittests src/lib.rs (target/debug/deps/silly_function-160869f38cff9166)
running 2 tests
test tests::this_test_will_fail ... FAILED
test tests::this_test_will_pass ... ok
successes:
---- tests::this_test_will_pass stdout ----
I got the value 4
successes:
tests::this_test_will_pass
failures:
---- tests::this_test_will_fail stdout ----
I got the value 8
thread 'tests::this_test_will_fail' panicked at 'assertion failed: `(left == right)`
left: `5`,
right: `10`', src/lib.rs:19:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::this_test_will_fail
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Running a Subset of Tests by Name
Sometimes, running a full test suite can take a long time. If you’re working on
code in a particular area, you might want to run only the tests pertaining to
that code. You can choose which tests to run by passing cargo test
the name
or names of the test(s) you want to run as an argument.
To demonstrate how to run a subset of tests, we’ll first create three tests for
our add_two
function, as shown in Listing 11-11, and choose which ones to run.
Filename: src/lib.rs
pub fn add_two(a: i32) -> i32 {
a + 2
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn add_two_and_two() {
assert_eq!(4, add_two(2));
}
#[test]
fn add_three_and_two() {
assert_eq!(5, add_two(3));
}
#[test]
fn one_hundred() {
assert_eq!(102, add_two(100));
}
}
If we run the tests without passing any arguments, as we saw earlier, all the tests will run in parallel:
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.62s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 3 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test tests::one_hundred ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running Single Tests
We can pass the name of any test function to cargo test
to run only that test:
$ cargo test one_hundred
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.69s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::one_hundred ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
Only the test with the name one_hundred
ran; the other two tests didn’t match
that name. The test output lets us know we had more tests that didn’t run by
displaying 2 filtered out
at the end.
We can’t specify the names of multiple tests in this way; only the first value
given to cargo test
will be used. But there is a way to run multiple tests.
Filtering to Run Multiple Tests
We can specify part of a test name, and any test whose name matches that value
will be run. For example, because two of our tests’ names contain add
, we can
run those two by running cargo test add
:
$ cargo test add
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.61s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests
test tests::add_three_and_two ... ok
test tests::add_two_and_two ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
This command ran all tests with add
in the name and filtered out the test
named one_hundred
. Also note that the module in which a test appears becomes
part of the test’s name, so we can run all the tests in a module by filtering
on the module’s name.
Ignoring Some Tests Unless Specifically Requested
Sometimes a few specific tests can be very time-consuming to execute, so you
might want to exclude them during most runs of cargo test
. Rather than
listing as arguments all tests you do want to run, you can instead annotate the
time-consuming tests using the ignore
attribute to exclude them, as shown
here:
Filename: src/lib.rs
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
#[test]
#[ignore]
fn expensive_test() {
// code that takes an hour to run
}
After #[test]
we add the #[ignore]
line to the test we want to exclude. Now
when we run our tests, it_works
runs, but expensive_test
doesn’t:
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.60s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 2 tests
test expensive_test ... ignored
test it_works ... ok
test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
The expensive_test
function is listed as ignored
. If we want to run only
the ignored tests, we can use cargo test -- --ignored
:
$ cargo test -- --ignored
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.61s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test expensive_test ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
By controlling which tests run, you can make sure your cargo test
results
will be fast. When you’re at a point where it makes sense to check the results
of the ignored
tests and you have time to wait for the results, you can run
cargo test -- --ignored
instead. If you want to run all tests whether they’re
ignored or not, you can run cargo test -- --include-ignored
.
Test Organization
As mentioned at the start of the chapter, testing is a complex discipline, and different people use different terminology and organization. The Rust community thinks about tests in terms of two main categories: unit tests and integration tests. Unit tests are small and more focused, testing one module in isolation at a time, and can test private interfaces. Integration tests are entirely external to your library and use your code in the same way any other external code would, using only the public interface and potentially exercising multiple modules per test.
Writing both kinds of tests is important to ensure that the pieces of your library are doing what you expect them to, separately and together.
Unit Tests
The purpose of unit tests is to test each unit of code in isolation from the
rest of the code to quickly pinpoint where code is and isn’t working as
expected. You’ll put unit tests in the src directory in each file with the
code that they’re testing. The convention is to create a module named tests
in each file to contain the test functions and to annotate the module with
cfg(test)
.
The Tests Module and #[cfg(test)]
The #[cfg(test)]
annotation on the tests module tells Rust to compile and run
the test code only when you run cargo test
, not when you run cargo build
.
This saves compile time when you only want to build the library and saves space
in the resulting compiled artifact because the tests are not included. You’ll
see that because integration tests go in a different directory, they don’t need
the #[cfg(test)]
annotation. However, because unit tests go in the same files
as the code, you’ll use #[cfg(test)]
to specify that they shouldn’t be
included in the compiled result.
Recall that when we generated the new adder
project in the first section of
this chapter, Cargo generated this code for us:
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}
This code is the automatically generated test module. The attribute cfg
stands for configuration and tells Rust that the following item should only
be included given a certain configuration option. In this case, the
configuration option is test
, which is provided by Rust for compiling and
running tests. By using the cfg
attribute, Cargo compiles our test code only
if we actively run the tests with cargo test
. This includes any helper
functions that might be within this module, in addition to the functions
annotated with #[test]
.
Testing Private Functions
There’s debate within the testing community about whether or not private
functions should be tested directly, and other languages make it difficult or
impossible to test private functions. Regardless of which testing ideology you
adhere to, Rust’s privacy rules do allow you to test private functions.
Consider the code in Listing 11-12 with the private function internal_adder
.
Filename: src/lib.rs
pub fn add_two(a: i32) -> i32 {
internal_adder(a, 2)
}
fn internal_adder(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn internal() {
assert_eq!(4, internal_adder(2, 2));
}
}
Note that the internal_adder
function is not marked as pub
. Tests are just
Rust code, and the tests
module is just another module. As we discussed in
the “Paths for Referring to an Item in the Module Tree”
section, items in child modules can use the items in their ancestor modules. In
this test, we bring all of the test
module’s parent’s items into scope with
use super::*
, and then the test can call internal_adder
. If you don’t think
private functions should be tested, there’s nothing in Rust that will compel
you to do so.
Integration Tests
In Rust, integration tests are entirely external to your library. They use your library in the same way any other code would, which means they can only call functions that are part of your library’s public API. Their purpose is to test whether many parts of your library work together correctly. Units of code that work correctly on their own could have problems when integrated, so test coverage of the integrated code is important as well. To create integration tests, you first need a tests directory.
The tests Directory
We create a tests directory at the top level of our project directory, next to src. Cargo knows to look for integration test files in this directory. We can then make as many test files as we want, and Cargo will compile each of the files as an individual crate.
Let’s create an integration test. With the code in Listing 11-12 still in the src/lib.rs file, make a tests directory, and create a new file named tests/integration_test.rs. Your directory structure should look like this:
adder
├── Cargo.lock
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
└── integration_test.rs
Enter the code in Listing 11-13 into the tests/integration_test.rs file:
Filename: tests/integration_test.rs
use adder;
#[test]
fn it_adds_two() {
assert_eq!(4, adder::add_two(2));
}
Each file in the tests
directory is a separate crate, so we need to bring our
library into each test crate’s scope. For that reason we add use adder
at the
top of the code, which we didn’t need in the unit tests.
We don’t need to annotate any code in tests/integration_test.rs with
#[cfg(test)]
. Cargo treats the tests
directory specially and compiles files
in this directory only when we run cargo test
. Run cargo test
now:
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 1.31s
Running unittests src/lib.rs (target/debug/deps/adder-1082c4b063a8fbe6)
running 1 test
test tests::internal ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/integration_test.rs (target/debug/deps/integration_test-1082c4b063a8fbe6)
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
The three sections of output include the unit tests, the integration test, and the doc tests. Note that if any test in a section fails, the following sections will not be run. For example, if a unit test fails, there won’t be any output for integration and doc tests because those tests will only be run if all unit tests are passing.
The first section for the unit tests is the same as we’ve been seeing: one line
for each unit test (one named internal
that we added in Listing 11-12) and
then a summary line for the unit tests.
The integration tests section starts with the line Running tests/integration_test.rs
. Next, there is a line for each test function in
that integration test and a summary line for the results of the integration
test just before the Doc-tests adder
section starts.
Each integration test file has its own section, so if we add more files in the tests directory, there will be more integration test sections.
We can still run a particular integration test function by specifying the test
function’s name as an argument to cargo test
. To run all the tests in a
particular integration test file, use the --test
argument of cargo test
followed by the name of the file:
$ cargo test --test integration_test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.64s
Running tests/integration_test.rs (target/debug/deps/integration_test-82e7799c1bc62298)
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
This command runs only the tests in the tests/integration_test.rs file.
Submodules in Integration Tests
As you add more integration tests, you might want to make more files in the tests directory to help organize them; for example, you can group the test functions by the functionality they’re testing. As mentioned earlier, each file in the tests directory is compiled as its own separate crate, which is useful for creating separate scopes to more closely imitate the way end users will be using your crate. However, this means files in the tests directory don’t share the same behavior as files in src do, as you learned in Chapter 7 regarding how to separate code into modules and files.
The different behavior of tests directory files is most noticeable when you
have a set of helper functions to use in multiple integration test files and
you try to follow the steps in the “Separating Modules into Different
Files” section of Chapter 7 to
extract them into a common module. For example, if we create tests/common.rs
and place a function named setup
in it, we can add some code to setup
that
we want to call from multiple test functions in multiple test files:
Filename: tests/common.rs
pub fn setup() {
// setup code specific to your library's tests would go here
}
When we run the tests again, we’ll see a new section in the test output for the
common.rs file, even though this file doesn’t contain any test functions nor
did we call the setup
function from anywhere:
$ cargo test
Compiling adder v0.1.0 (file:///projects/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.89s
Running unittests src/lib.rs (target/debug/deps/adder-92948b65e88960b4)
running 1 test
test tests::internal ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/common.rs (target/debug/deps/common-92948b65e88960b4)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/integration_test.rs (target/debug/deps/integration_test-92948b65e88960b4)
running 1 test
test it_adds_two ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Having common
appear in the test results with running 0 tests
displayed for
it is not what we wanted. We just wanted to share some code with the other
integration test files.
To avoid having common
appear in the test output, instead of creating
tests/common.rs, we’ll create tests/common/mod.rs. The project directory
now looks like this:
├── Cargo.lock
├── Cargo.toml
├── src
│ └── lib.rs
└── tests
├── common
│ └── mod.rs
└── integration_test.rs
This is the older naming convention that Rust also understands that we
mentioned in the “Alternate File Paths” section of
Chapter 7. Naming the file this way tells Rust not to treat the common
module
as an integration test file. When we move the setup
function code into
tests/common/mod.rs and delete the tests/common.rs file, the section in the
test output will no longer appear. Files in subdirectories of the tests
directory don’t get compiled as separate crates or have sections in the test
output.
After we’ve created tests/common/mod.rs, we can use it from any of the
integration test files as a module. Here’s an example of calling the setup
function from the it_adds_two
test in tests/integration_test.rs:
Filename: tests/integration_test.rs
use adder;
mod common;
#[test]
fn it_adds_two() {
common::setup();
assert_eq!(4, adder::add_two(2));
}
Note that the mod common;
declaration is the same as the module declaration
we demonstrated in Listing 7-21. Then in the test function, we can call the
common::setup()
function.
Integration Tests for Binary Crates
If our project is a binary crate that only contains a src/main.rs file and
doesn’t have a src/lib.rs file, we can’t create integration tests in the
tests directory and bring functions defined in the src/main.rs file into
scope with a use
statement. Only library crates expose functions that other
crates can use; binary crates are meant to be run on their own.
This is one of the reasons Rust projects that provide a binary have a
straightforward src/main.rs file that calls logic that lives in the
src/lib.rs file. Using that structure, integration tests can test the
library crate with use
to make the important functionality available.
If the important functionality works, the small amount of code in the
src/main.rs file will work as well, and that small amount of code doesn’t
need to be tested.
Summary
Rust’s testing features provide a way to specify how code should function to ensure it continues to work as you expect, even as you make changes. Unit tests exercise different parts of a library separately and can test private implementation details. Integration tests check that many parts of the library work together correctly, and they use the library’s public API to test the code in the same way external code will use it. Even though Rust’s type system and ownership rules help prevent some kinds of bugs, tests are still important to reduce logic bugs having to do with how your code is expected to behave.
Let’s combine the knowledge you learned in this chapter and in previous chapters to work on a project!
An I/O Project: Building a Command Line Program
This chapter is a recap of the many skills you’ve learned so far and an exploration of a few more standard library features. We’ll build a command line tool that interacts with file and command line input/output to practice some of the Rust concepts you now have under your belt.
Rust’s speed, safety, single binary output, and cross-platform support make it
an ideal language for creating command line tools, so for our project, we’ll
make our own version of the classic command line search tool grep
(globally search a regular expression and print). In the
simplest use case, grep
searches a specified file for a specified string. To
do so, grep
takes as its arguments a file path and a string. Then it reads
the file, finds lines in that file that contain the string argument, and prints
those lines.
Along the way, we’ll show how to make our command line tool use the terminal
features that many other command line tools use. We’ll read the value of an
environment variable to allow the user to configure the behavior of our tool.
We’ll also print error messages to the standard error console stream (stderr
)
instead of standard output (stdout
), so, for example, the user can redirect
successful output to a file while still seeing error messages onscreen.
One Rust community member, Andrew Gallant, has already created a fully
featured, very fast version of grep
, called ripgrep
. By comparison, our
version will be fairly simple, but this chapter will give you some of the
background knowledge you need to understand a real-world project such as
ripgrep
.
Our grep
project will combine a number of concepts you’ve learned so far:
- Organizing code (using what you learned about modules in Chapter 7)
- Using vectors and strings (collections, Chapter 8)
- Handling errors (Chapter 9)
- Using traits and lifetimes where appropriate (Chapter 10)
- Writing tests (Chapter 11)
We’ll also briefly introduce closures, iterators, and trait objects, which Chapters 13 and 17 will cover in detail.
Accepting Command Line Arguments
Let’s create a new project with, as always, cargo new
. We’ll call our project
minigrep
to distinguish it from the grep
tool that you might already have
on your system.
$ cargo new minigrep
Created binary (application) `minigrep` project
$ cd minigrep
The first task is to make minigrep
accept its two command line arguments: the
file path and a string to search for. That is, we want to be able to run our
program with cargo run
, two hyphens to indicate the following arguments are
for our program rather than for cargo
, a string to search for, and a path to
a file to search in, like so:
$ cargo run -- searchstring example-filename.txt
Right now, the program generated by cargo new
cannot process arguments we
give it. Some existing libraries on crates.io can help
with writing a program that accepts command line arguments, but because you’re
just learning this concept, let’s implement this capability ourselves.
Reading the Argument Values
To enable minigrep
to read the values of command line arguments we pass to
it, we’ll need the std::env::args
function provided in Rust’s standard
library. This function returns an iterator of the command line arguments passed
to minigrep
. We’ll cover iterators fully in Chapter 13. For now, you only need to know two details about iterators: iterators
produce a series of values, and we can call the collect
method on an iterator
to turn it into a collection, such as a vector, that contains all the elements
the iterator produces.
The code in Listing 12-1 allows your minigrep
program to read any command
line arguments passed to it and then collect the values into a vector.
Filename: src/main.rs
use std::env; fn main() { let args: Vec<String> = env::args().collect(); dbg!(args); }
First, we bring the std::env
module into scope with a use
statement so we
can use its args
function. Notice that the std::env::args
function is
nested in two levels of modules. As we discussed in Chapter
7, in cases where the desired function is
nested in more than one module, we’ve chosen to bring the parent module into
scope rather than the function. By doing so, we can easily use other functions
from std::env
. It’s also less ambiguous than adding use std::env::args
and
then calling the function with just args
, because args
might easily be
mistaken for a function that’s defined in the current module.
The
args
Function and Invalid UnicodeNote that
std::env::args
will panic if any argument contains invalid Unicode. If your program needs to accept arguments containing invalid Unicode, usestd::env::args_os
instead. That function returns an iterator that producesOsString
values instead ofString
values. We’ve chosen to usestd::env::args
here for simplicity, becauseOsString
values differ per platform and are more complex to work with thanString
values.
On the first line of main
, we call env::args
, and we immediately use
collect
to turn the iterator into a vector containing all the values produced
by the iterator. We can use the collect
function to create many kinds of
collections, so we explicitly annotate the type of args
to specify that we
want a vector of strings. Although we very rarely need to annotate types in
Rust, collect
is one function you do often need to annotate because Rust
isn’t able to infer the kind of collection you want.
Finally, we print the vector using the debug macro. Let’s try running the code first with no arguments and then with two arguments:
$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.61s
Running `target/debug/minigrep`
[src/main.rs:5] args = [
"target/debug/minigrep",
]
$ cargo run -- needle haystack
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 1.57s
Running `target/debug/minigrep needle haystack`
[src/main.rs:5] args = [
"target/debug/minigrep",
"needle",
"haystack",
]
Notice that the first value in the vector is "target/debug/minigrep"
, which
is the name of our binary. This matches the behavior of the arguments list in
C, letting programs use the name by which they were invoked in their execution.
It’s often convenient to have access to the program name in case you want to
print it in messages or change behavior of the program based on what command
line alias was used to invoke the program. But for the purposes of this
chapter, we’ll ignore it and save only the two arguments we need.
Saving the Argument Values in Variables
The program is currently able to access the values specified as command line arguments. Now we need to save the values of the two arguments in variables so we can use the values throughout the rest of the program. We do that in Listing 12-2.
Filename: src/main.rs
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let query = &args[1];
let file_path = &args[2];
println!("Searching for {}", query);
println!("In file {}", file_path);
}
As we saw when we printed the vector, the program’s name takes up the first
value in the vector at args[0]
, so we’re starting arguments at index 1
. The
first argument minigrep
takes is the string we’re searching for, so we put a
reference to the first argument in the variable query
. The second argument
will be the file path, so we put a reference to the second argument in the
variable file_path
.
We temporarily print the values of these variables to prove that the code is
working as we intend. Let’s run this program again with the arguments test
and sample.txt
:
$ cargo run -- test sample.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep test sample.txt`
Searching for test
In file sample.txt
Great, the program is working! The values of the arguments we need are being saved into the right variables. Later we’ll add some error handling to deal with certain potential erroneous situations, such as when the user provides no arguments; for now, we’ll ignore that situation and work on adding file-reading capabilities instead.
Reading a File
Now we’ll add functionality to read the file specified in the file_path
argument. First, we need a sample file to test it with: we’ll use a file with a
small amount of text over multiple lines with some repeated words. Listing 12-3
has an Emily Dickinson poem that will work well! Create a file called
poem.txt at the root level of your project, and enter the poem “I’m Nobody!
Who are you?”
Filename: poem.txt
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
With the text in place, edit src/main.rs and add code to read the file, as shown in Listing 12-4.
Filename: src/main.rs
use std::env;
use std::fs;
fn main() {
// --snip--
let args: Vec<String> = env::args().collect();
let query = &args[1];
let file_path = &args[2];
println!("Searching for {}", query);
println!("In file {}", file_path);
let contents = fs::read_to_string(file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
First, we bring in a relevant part of the standard library with a use
statement: we need std::fs
to handle files.
In main
, the new statement fs::read_to_string
takes the file_path
, opens
that file, and returns a std::io::Result<String>
of the file’s contents.
After that, we again add a temporary println!
statement that prints the value
of contents
after the file is read, so we can check that the program is
working so far.
Let’s run this code with any string as the first command line argument (because we haven’t implemented the searching part yet) and the poem.txt file as the second argument:
$ cargo run -- the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
Great! The code read and then printed the contents of the file. But the code
has a few flaws. At the moment, the main
function has multiple
responsibilities: generally, functions are clearer and easier to maintain if
each function is responsible for only one idea. The other problem is that we’re
not handling errors as well as we could. The program is still small, so these
flaws aren’t a big problem, but as the program grows, it will be harder to fix
them cleanly. It’s good practice to begin refactoring early on when developing
a program, because it’s much easier to refactor smaller amounts of code. We’ll
do that next.
Refactoring to Improve Modularity and Error Handling
To improve our program, we’ll fix four problems that have to do with the
program’s structure and how it’s handling potential errors. First, our main
function now performs two tasks: it parses arguments and reads files. As our
program grows, the number of separate tasks the main
function handles will
increase. As a function gains responsibilities, it becomes more difficult to
reason about, harder to test, and harder to change without breaking one of its
parts. It’s best to separate functionality so each function is responsible for
one task.
This issue also ties into the second problem: although query
and file_path
are configuration variables to our program, variables like contents
are used
to perform the program’s logic. The longer main
becomes, the more variables
we’ll need to bring into scope; the more variables we have in scope, the harder
it will be to keep track of the purpose of each. It’s best to group the
configuration variables into one structure to make their purpose clear.
The third problem is that we’ve used expect
to print an error message when
reading the file fails, but the error message just prints Should have been able to read the file
. Reading a file can fail in a number of ways: for
example, the file could be missing, or we might not have permission to open it.
Right now, regardless of the situation, we’d print the same error message for
everything, which wouldn’t give the user any information!
Fourth, we use expect
repeatedly to handle different errors, and if the user
runs our program without specifying enough arguments, they’ll get an index out of bounds
error from Rust that doesn’t clearly explain the problem. It would
be best if all the error-handling code were in one place so future maintainers
had only one place to consult the code if the error-handling logic needed to
change. Having all the error-handling code in one place will also ensure that
we’re printing messages that will be meaningful to our end users.
Let’s address these four problems by refactoring our project.
Separation of Concerns for Binary Projects
The organizational problem of allocating responsibility for multiple tasks to
the main
function is common to many binary projects. As a result, the Rust
community has developed guidelines for splitting the separate concerns of a
binary program when main
starts getting large. This process has the following
steps:
- Split your program into a main.rs and a lib.rs and move your program’s logic to lib.rs.
- As long as your command line parsing logic is small, it can remain in main.rs.
- When the command line parsing logic starts getting complicated, extract it from main.rs and move it to lib.rs.
The responsibilities that remain in the main
function after this process
should be limited to the following:
- Calling the command line parsing logic with the argument values
- Setting up any other configuration
- Calling a
run
function in lib.rs - Handling the error if
run
returns an error
This pattern is about separating concerns: main.rs handles running the
program, and lib.rs handles all the logic of the task at hand. Because you
can’t test the main
function directly, this structure lets you test all of
your program’s logic by moving it into functions in lib.rs. The code that
remains in main.rs will be small enough to verify its correctness by reading
it. Let’s rework our program by following this process.
Extracting the Argument Parser
We’ll extract the functionality for parsing arguments into a function that
main
will call to prepare for moving the command line parsing logic to
src/lib.rs. Listing 12-5 shows the new start of main
that calls a new
function parse_config
, which we’ll define in src/main.rs for the moment.
Filename: src/main.rs
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let (query, file_path) = parse_config(&args);
// --snip--
println!("Searching for {}", query);
println!("In file {}", file_path);
let contents = fs::read_to_string(file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
fn parse_config(args: &[String]) -> (&str, &str) {
let query = &args[1];
let file_path = &args[2];
(query, file_path)
}
We’re still collecting the command line arguments into a vector, but instead of
assigning the argument value at index 1 to the variable query
and the
argument value at index 2 to the variable file_path
within the main
function, we pass the whole vector to the parse_config
function. The
parse_config
function then holds the logic that determines which argument
goes in which variable and passes the values back to main
. We still create
the query
and file_path
variables in main
, but main
no longer has the
responsibility of determining how the command line arguments and variables
correspond.
This rework may seem like overkill for our small program, but we’re refactoring in small, incremental steps. After making this change, run the program again to verify that the argument parsing still works. It’s good to check your progress often, to help identify the cause of problems when they occur.
Grouping Configuration Values
We can take another small step to improve the parse_config
function further.
At the moment, we’re returning a tuple, but then we immediately break that
tuple into individual parts again. This is a sign that perhaps we don’t have
the right abstraction yet.
Another indicator that shows there’s room for improvement is the config
part
of parse_config
, which implies that the two values we return are related and
are both part of one configuration value. We’re not currently conveying this
meaning in the structure of the data other than by grouping the two values into
a tuple; we’ll instead put the two values into one struct and give each of the
struct fields a meaningful name. Doing so will make it easier for future
maintainers of this code to understand how the different values relate to each
other and what their purpose is.
Listing 12-6 shows the improvements to the parse_config
function.
Filename: src/main.rs
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let config = parse_config(&args);
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
// --snip--
println!("With text:\n{contents}");
}
struct Config {
query: String,
file_path: String,
}
fn parse_config(args: &[String]) -> Config {
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}
We’ve added a struct named Config
defined to have fields named query
and
file_path
. The signature of parse_config
now indicates that it returns a
Config
value. In the body of parse_config
, where we used to return
string slices that reference String
values in args
, we now define Config
to contain owned String
values. The args
variable in main
is the owner of
the argument values and is only letting the parse_config
function borrow
them, which means we’d violate Rust’s borrowing rules if Config
tried to take
ownership of the values in args
.
There are a number of ways we could manage the String
data; the easiest,
though somewhat inefficient, route is to call the clone
method on the values.
This will make a full copy of the data for the Config
instance to own, which
takes more time and memory than storing a reference to the string data.
However, cloning the data also makes our code very straightforward because we
don’t have to manage the lifetimes of the references; in this circumstance,
giving up a little performance to gain simplicity is a worthwhile trade-off.
The Trade-Offs of Using
clone
There’s a tendency among many Rustaceans to avoid using
clone
to fix ownership problems because of its runtime cost. In Chapter 13, you’ll learn how to use more efficient methods in this type of situation. But for now, it’s okay to copy a few strings to continue making progress because you’ll make these copies only once and your file path and query string are very small. It’s better to have a working program that’s a bit inefficient than to try to hyperoptimize code on your first pass. As you become more experienced with Rust, it’ll be easier to start with the most efficient solution, but for now, it’s perfectly acceptable to callclone
.
We’ve updated main
so it places the instance of Config
returned by
parse_config
into a variable named config
, and we updated the code that
previously used the separate query
and file_path
variables so it now uses
the fields on the Config
struct instead.
Now our code more clearly conveys that query
and file_path
are related and
that their purpose is to configure how the program will work. Any code that
uses these values knows to find them in the config
instance in the fields
named for their purpose.
Creating a Constructor for Config
So far, we’ve extracted the logic responsible for parsing the command line
arguments from main
and placed it in the parse_config
function. Doing so
helped us to see that the query
and file_path
values were related and that
relationship should be conveyed in our code. We then added a Config
struct to
name the related purpose of query
and file_path
and to be able to return the
values’ names as struct field names from the parse_config
function.
So now that the purpose of the parse_config
function is to create a Config
instance, we can change parse_config
from a plain function to a function
named new
that is associated with the Config
struct. Making this change
will make the code more idiomatic. We can create instances of types in the
standard library, such as String
, by calling String::new
. Similarly, by
changing parse_config
into a new
function associated with Config
, we’ll
be able to create instances of Config
by calling Config::new
. Listing 12-7
shows the changes we need to make.
Filename: src/main.rs
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args);
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
// --snip--
}
// --snip--
struct Config {
query: String,
file_path: String,
}
impl Config {
fn new(args: &[String]) -> Config {
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}
}
We’ve updated main
where we were calling parse_config
to instead call
Config::new
. We’ve changed the name of parse_config
to new
and moved it
within an impl
block, which associates the new
function with Config
. Try
compiling this code again to make sure it works.
Fixing the Error Handling
Now we’ll work on fixing our error handling. Recall that attempting to access
the values in the args
vector at index 1 or index 2 will cause the program to
panic if the vector contains fewer than three items. Try running the program
without any arguments; it will look like this:
$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep`
thread 'main' panicked at 'index out of bounds: the len is 1 but the index is 1', src/main.rs:27:21
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The line index out of bounds: the len is 1 but the index is 1
is an error
message intended for programmers. It won’t help our end users understand what
they should do instead. Let’s fix that now.
Improving the Error Message
In Listing 12-8, we add a check in the new
function that will verify that the
slice is long enough before accessing index 1 and 2. If the slice isn’t long
enough, the program panics and displays a better error message.
Filename: src/main.rs
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args);
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
struct Config {
query: String,
file_path: String,
}
impl Config {
// --snip--
fn new(args: &[String]) -> Config {
if args.len() < 3 {
panic!("not enough arguments");
}
// --snip--
let query = args[1].clone();
let file_path = args[2].clone();
Config { query, file_path }
}
}
This code is similar to the Guess::new
function we wrote in Listing
9-13, where we called panic!
when the
value
argument was out of the range of valid values. Instead of checking for
a range of values here, we’re checking that the length of args
is at least 3
and the rest of the function can operate under the assumption that this
condition has been met. If args
has fewer than three items, this condition
will be true, and we call the panic!
macro to end the program immediately.
With these extra few lines of code in new
, let’s run the program without any
arguments again to see what the error looks like now:
$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep`
thread 'main' panicked at 'not enough arguments', src/main.rs:26:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
This output is better: we now have a reasonable error message. However, we also
have extraneous information we don’t want to give to our users. Perhaps using
the technique we used in Listing 9-13 isn’t the best to use here: a call to
panic!
is more appropriate for a programming problem than a usage problem,
as discussed in Chapter 9. Instead,
we’ll use the other technique you learned about in Chapter 9—returning a
Result
that indicates either success or an error.
Returning a Result
Instead of Calling panic!
We can instead return a Result
value that will contain a Config
instance in
the successful case and will describe the problem in the error case. We’re also
going to change the function name from new
to build
because many
programmers expect new
functions to never fail. When Config::build
is
communicating to main
, we can use the Result
type to signal there was a
problem. Then we can change main
to convert an Err
variant into a more
practical error for our users without the surrounding text about thread 'main'
and RUST_BACKTRACE
that a call to panic!
causes.
Listing 12-9 shows the changes we need to make to the return value of the
function we’re now calling Config::build
and the body of the function needed
to return a Result
. Note that this won’t compile until we update main
as
well, which we’ll do in the next listing.
Filename: src/main.rs
use std::env;
use std::fs;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args);
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
Our build
function returns a Result
with a Config
instance in the success
case and a &'static str
in the error case. Our error values will always be
string literals that have the 'static
lifetime.
We’ve made two changes in the body of the function: instead of calling panic!
when the user doesn’t pass enough arguments, we now return an Err
value, and
we’ve wrapped the Config
return value in an Ok
. These changes make the
function conform to its new type signature.
Returning an Err
value from Config::build
allows the main
function to
handle the Result
value returned from the build
function and exit the
process more cleanly in the error case.
Calling Config::build
and Handling Errors
To handle the error case and print a user-friendly message, we need to update
main
to handle the Result
being returned by Config::build
, as shown in
Listing 12-10. We’ll also take the responsibility of exiting the command line
tool with a nonzero error code away from panic!
and instead implement it by
hand. A nonzero exit status is a convention to signal to the process that
called our program that the program exited with an error state.
Filename: src/main.rs
use std::env;
use std::fs;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
// --snip--
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
In this listing, we’ve used a method we haven’t covered in detail yet:
unwrap_or_else
, which is defined on Result<T, E>
by the standard library.
Using unwrap_or_else
allows us to define some custom, non-panic!
error
handling. If the Result
is an Ok
value, this method’s behavior is similar
to unwrap
: it returns the inner value Ok
is wrapping. However, if the value
is an Err
value, this method calls the code in the closure, which is an
anonymous function we define and pass as an argument to unwrap_or_else
. We’ll
cover closures in more detail in Chapter 13. For now,
you just need to know that unwrap_or_else
will pass the inner value of the
Err
, which in this case is the static string "not enough arguments"
that we
added in Listing 12-9, to our closure in the argument err
that appears
between the vertical pipes. The code in the closure can then use the err
value when it runs.
We’ve added a new use
line to bring process
from the standard library into
scope. The code in the closure that will be run in the error case is only two
lines: we print the err
value and then call process::exit
. The
process::exit
function will stop the program immediately and return the
number that was passed as the exit status code. This is similar to the
panic!
-based handling we used in Listing 12-8, but we no longer get all the
extra output. Let’s try it:
$ cargo run
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/minigrep`
Problem parsing arguments: not enough arguments
Great! This output is much friendlier for our users.
Extracting Logic from main
Now that we’ve finished refactoring the configuration parsing, let’s turn to
the program’s logic. As we stated in “Separation of Concerns for Binary
Projects”, we’ll
extract a function named run
that will hold all the logic currently in the
main
function that isn’t involved with setting up configuration or handling
errors. When we’re done, main
will be concise and easy to verify by
inspection, and we’ll be able to write tests for all the other logic.
Listing 12-11 shows the extracted run
function. For now, we’re just making
the small, incremental improvement of extracting the function. We’re still
defining the function in src/main.rs.
Filename: src/main.rs
use std::env;
use std::fs;
use std::process;
fn main() {
// --snip--
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
run(config);
}
fn run(config: Config) {
let contents = fs::read_to_string(config.file_path)
.expect("Should have been able to read the file");
println!("With text:\n{contents}");
}
// --snip--
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
The run
function now contains all the remaining logic from main
, starting
from reading the file. The run
function takes the Config
instance as an
argument.
Returning Errors from the run
Function
With the remaining program logic separated into the run
function, we can
improve the error handling, as we did with Config::build
in Listing 12-9.
Instead of allowing the program to panic by calling expect
, the run
function will return a Result<T, E>
when something goes wrong. This will let
us further consolidate the logic around handling errors into main
in a
user-friendly way. Listing 12-12 shows the changes we need to make to the
signature and body of run
.
Filename: src/main.rs
use std::env;
use std::fs;
use std::process;
use std::error::Error;
// --snip--
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
run(config);
}
fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n{contents}");
Ok(())
}
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
We’ve made three significant changes here. First, we changed the return type of
the run
function to Result<(), Box<dyn Error>>
. This function previously
returned the unit type, ()
, and we keep that as the value returned in the
Ok
case.
For the error type, we used the trait object Box<dyn Error>
(and we’ve
brought std::error::Error
into scope with a use
statement at the top).
We’ll cover trait objects in Chapter 17. For now, just
know that Box<dyn Error>
means the function will return a type that
implements the Error
trait, but we don’t have to specify what particular type
the return value will be. This gives us flexibility to return error values that
may be of different types in different error cases. The dyn
keyword is short
for “dynamic.”
Second, we’ve removed the call to expect
in favor of the ?
operator, as we
talked about in Chapter 9. Rather than
panic!
on an error, ?
will return the error value from the current function
for the caller to handle.
Third, the run
function now returns an Ok
value in the success case.
We’ve declared the run
function’s success type as ()
in the signature,
which means we need to wrap the unit type value in the Ok
value. This
Ok(())
syntax might look a bit strange at first, but using ()
like this is
the idiomatic way to indicate that we’re calling run
for its side effects
only; it doesn’t return a value we need.
When you run this code, it will compile but will display a warning:
$ cargo run the poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
warning: unused `Result` that must be used
--> src/main.rs:19:5
|
19 | run(config);
| ^^^^^^^^^^^
|
= note: this `Result` may be an `Err` variant, which should be handled
= note: `#[warn(unused_must_use)]` on by default
warning: `minigrep` (bin "minigrep") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.71s
Running `target/debug/minigrep the poem.txt`
Searching for the
In file poem.txt
With text:
I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.
How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
Rust tells us that our code ignored the Result
value and the Result
value
might indicate that an error occurred. But we’re not checking to see whether or
not there was an error, and the compiler reminds us that we probably meant to
have some error-handling code here! Let’s rectify that problem now.
Handling Errors Returned from run
in main
We’ll check for errors and handle them using a technique similar to one we used
with Config::build
in Listing 12-10, but with a slight difference:
Filename: src/main.rs
use std::env;
use std::error::Error;
use std::fs;
use std::process;
fn main() {
// --snip--
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
if let Err(e) = run(config) {
println!("Application error: {e}");
process::exit(1);
}
}
fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n{contents}");
Ok(())
}
struct Config {
query: String,
file_path: String,
}
impl Config {
fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
We use if let
rather than unwrap_or_else
to check whether run
returns an
Err
value and call process::exit(1)
if it does. The run
function doesn’t
return a value that we want to unwrap
in the same way that Config::build
returns the Config
instance. Because run
returns ()
in the success case,
we only care about detecting an error, so we don’t need unwrap_or_else
to
return the unwrapped value, which would only be ()
.
The bodies of the if let
and the unwrap_or_else
functions are the same in
both cases: we print the error and exit.
Splitting Code into a Library Crate
Our minigrep
project is looking good so far! Now we’ll split the
src/main.rs file and put some code into the src/lib.rs file. That way we
can test the code and have a src/main.rs file with fewer responsibilities.
Let’s move all the code that isn’t the main
function from src/main.rs to
src/lib.rs:
- The
run
function definition - The relevant
use
statements - The definition of
Config
- The
Config::build
function definition
The contents of src/lib.rs should have the signatures shown in Listing 12-13 (we’ve omitted the bodies of the functions for brevity). Note that this won’t compile until we modify src/main.rs in Listing 12-14.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
// --snip--
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
// --snip--
let contents = fs::read_to_string(config.file_path)?;
println!("With text:\n{contents}");
Ok(())
}
We’ve made liberal use of the pub
keyword: on Config
, on its fields and its
build
method, and on the run
function. We now have a library crate that has
a public API we can test!
Now we need to bring the code we moved to src/lib.rs into the scope of the binary crate in src/main.rs, as shown in Listing 12-14.
Filename: src/main.rs
use std::env;
use std::process;
use minigrep::Config;
fn main() {
// --snip--
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {err}");
process::exit(1);
});
println!("Searching for {}", config.query);
println!("In file {}", config.file_path);
if let Err(e) = minigrep::run(config) {
// --snip--
println!("Application error: {e}");
process::exit(1);
}
}
We add a use minigrep::Config
line to bring the Config
type from the
library crate into the binary crate’s scope, and we prefix the run
function
with our crate name. Now all the functionality should be connected and should
work. Run the program with cargo run
and make sure everything works
correctly.
Whew! That was a lot of work, but we’ve set ourselves up for success in the future. Now it’s much easier to handle errors, and we’ve made the code more modular. Almost all of our work will be done in src/lib.rs from here on out.
Let’s take advantage of this newfound modularity by doing something that would have been difficult with the old code but is easy with the new code: we’ll write some tests!
Developing the Library’s Functionality with Test-Driven Development
Now that we’ve extracted the logic into src/lib.rs and left the argument collecting and error handling in src/main.rs, it’s much easier to write tests for the core functionality of our code. We can call functions directly with various arguments and check return values without having to call our binary from the command line.
In this section, we’ll add the searching logic to the minigrep
program
using the test-driven development (TDD) process with the following steps:
- Write a test that fails and run it to make sure it fails for the reason you expect.
- Write or modify just enough code to make the new test pass.
- Refactor the code you just added or changed and make sure the tests continue to pass.
- Repeat from step 1!
Though it’s just one of many ways to write software, TDD can help drive code design. Writing the test before you write the code that makes the test pass helps to maintain high test coverage throughout the process.
We’ll test drive the implementation of the functionality that will actually do
the searching for the query string in the file contents and produce a list of
lines that match the query. We’ll add this functionality in a function called
search
.
Writing a Failing Test
Because we don’t need them anymore, let’s remove the println!
statements from
src/lib.rs and src/main.rs that we used to check the program’s behavior.
Then, in src/lib.rs, add a tests
module with a test function, as we did in
Chapter 11. The test function specifies the
behavior we want the search
function to have: it will take a query and the
text to search, and it will return only the lines from the text that contain
the query. Listing 12-15 shows this test, which won’t compile yet.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
This test searches for the string "duct"
. The text we’re searching is three
lines, only one of which contains "duct"
(Note that the backslash after the
opening double quote tells Rust not to put a newline character at the beginning
of the contents of this string literal). We assert that the value returned from
the search
function contains only the line we expect.
We aren’t yet able to run this test and watch it fail because the test doesn’t
even compile: the search
function doesn’t exist yet! In accordance with TDD
principles, we’ll add just enough code to get the test to compile and run by
adding a definition of the search
function that always returns an empty
vector, as shown in Listing 12-16. Then the test should compile and fail
because an empty vector doesn’t match a vector containing the line "safe, fast, productive."
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
vec![]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
Notice that we need to define an explicit lifetime 'a
in the signature of
search
and use that lifetime with the contents
argument and the return
value. Recall in Chapter 10 that the lifetime
parameters specify which argument lifetime is connected to the lifetime of the
return value. In this case, we indicate that the returned vector should contain
string slices that reference slices of the argument contents
(rather than the
argument query
).
In other words, we tell Rust that the data returned by the search
function
will live as long as the data passed into the search
function in the
contents
argument. This is important! The data referenced by a slice needs
to be valid for the reference to be valid; if the compiler assumes we’re making
string slices of query
rather than contents
, it will do its safety checking
incorrectly.
If we forget the lifetime annotations and try to compile this function, we’ll get this error:
$ cargo build
Compiling minigrep v0.1.0 (file:///projects/minigrep)
error[E0106]: missing lifetime specifier
--> src/lib.rs:28:51
|
28 | pub fn search(query: &str, contents: &str) -> Vec<&str> {
| ---- ---- ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `query` or `contents`
help: consider introducing a named lifetime parameter
|
28 | pub fn search<'a>(query: &'a str, contents: &'a str) -> Vec<&'a str> {
| ++++ ++ ++ ++
For more information about this error, try `rustc --explain E0106`.
error: could not compile `minigrep` due to previous error
Rust can’t possibly know which of the two arguments we need, so we need to tell
it explicitly. Because contents
is the argument that contains all of our text
and we want to return the parts of that text that match, we know contents
is
the argument that should be connected to the return value using the lifetime
syntax.
Other programming languages don’t require you to connect arguments to return values in the signature, but this practice will get easier over time. You might want to compare this example with the “Validating References with Lifetimes” section in Chapter 10.
Now let’s run the test:
$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished test [unoptimized + debuginfo] target(s) in 0.97s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 1 test
test tests::one_result ... FAILED
failures:
---- tests::one_result stdout ----
thread 'tests::one_result' panicked at 'assertion failed: `(left == right)`
left: `["safe, fast, productive."]`,
right: `[]`', src/lib.rs:44:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::one_result
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Great, the test fails, exactly as we expected. Let’s get the test to pass!
Writing Code to Pass the Test
Currently, our test is failing because we always return an empty vector. To fix
that and implement search
, our program needs to follow these steps:
- Iterate through each line of the contents.
- Check whether the line contains our query string.
- If it does, add it to the list of values we’re returning.
- If it doesn’t, do nothing.
- Return the list of results that match.
Let’s work through each step, starting with iterating through lines.
Iterating Through Lines with the lines
Method
Rust has a helpful method to handle line-by-line iteration of strings,
conveniently named lines
, that works as shown in Listing 12-17. Note this
won’t compile yet.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
for line in contents.lines() {
// do something with line
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
The lines
method returns an iterator. We’ll talk about iterators in depth in
Chapter 13, but recall that you saw this way
of using an iterator in Listing 3-5, where we used a
for
loop with an iterator to run some code on each item in a collection.
Searching Each Line for the Query
Next, we’ll check whether the current line contains our query string.
Fortunately, strings have a helpful method named contains
that does this for
us! Add a call to the contains
method in the search
function, as shown in
Listing 12-18. Note this still won’t compile yet.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
for line in contents.lines() {
if line.contains(query) {
// do something with line
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
At the moment, we’re building up functionality. To get it to compile, we need to return a value from the body as we indicated we would in the function signature.
Storing Matching Lines
To finish this function, we need a way to store the matching lines that we want
to return. For that, we can make a mutable vector before the for
loop and
call the push
method to store a line
in the vector. After the for
loop,
we return the vector, as shown in Listing 12-19.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
Now the search
function should return only the lines that contain query
,
and our test should pass. Let’s run the test:
$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished test [unoptimized + debuginfo] target(s) in 1.22s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 1 test
test tests::one_result ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests minigrep
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Our test passed, so we know it works!
At this point, we could consider opportunities for refactoring the implementation of the search function while keeping the tests passing to maintain the same functionality. The code in the search function isn’t too bad, but it doesn’t take advantage of some useful features of iterators. We’ll return to this example in Chapter 13, where we’ll explore iterators in detail, and look at how to improve it.
Using the search
Function in the run
Function
Now that the search
function is working and tested, we need to call search
from our run
function. We need to pass the config.query
value and the
contents
that run
reads from the file to the search
function. Then run
will print each line returned from search
:
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
for line in search(&config.query, &contents) {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
We’re still using a for
loop to return each line from search
and print it.
Now the entire program should work! Let’s try it out, first with a word that should return exactly one line from the Emily Dickinson poem, “frog”:
$ cargo run -- frog poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.38s
Running `target/debug/minigrep frog poem.txt`
How public, like a frog
Cool! Now let’s try a word that will match multiple lines, like “body”:
$ cargo run -- body poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep body poem.txt`
I'm nobody! Who are you?
Are you nobody, too?
How dreary to be somebody!
And finally, let’s make sure that we don’t get any lines when we search for a word that isn’t anywhere in the poem, such as “monomorphization”:
$ cargo run -- monomorphization poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep monomorphization poem.txt`
Excellent! We’ve built our own mini version of a classic tool and learned a lot about how to structure applications. We’ve also learned a bit about file input and output, lifetimes, testing, and command line parsing.
To round out this project, we’ll briefly demonstrate how to work with environment variables and how to print to standard error, both of which are useful when you’re writing command line programs.
Working with Environment Variables
We’ll improve minigrep
by adding an extra feature: an option for
case-insensitive searching that the user can turn on via an environment
variable. We could make this feature a command line option and require that
users enter it each time they want it to apply, but by instead making it an
environment variable, we allow our users to set the environment variable once
and have all their searches be case insensitive in that terminal session.
Writing a Failing Test for the Case-Insensitive search
Function
We first add a new search_case_insensitive
function that will be called when
the environment variable has a value. We’ll continue to follow the TDD process,
so the first step is again to write a failing test. We’ll add a new test for
the new search_case_insensitive
function and rename our old test from
one_result
to case_sensitive
to clarify the differences between the two
tests, as shown in Listing 12-20.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
for line in search(&config.query, &contents) {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
Note that we’ve edited the old test’s contents
too. We’ve added a new line
with the text "Duct tape."
using a capital D that shouldn’t match the query
"duct"
when we’re searching in a case-sensitive manner. Changing the old test
in this way helps ensure that we don’t accidentally break the case-sensitive
search functionality that we’ve already implemented. This test should pass now
and should continue to pass as we work on the case-insensitive search.
The new test for the case-insensitive search uses "rUsT"
as its query. In
the search_case_insensitive
function we’re about to add, the query "rUsT"
should match the line containing "Rust:"
with a capital R and match the line
"Trust me."
even though both have different casing from the query. This is
our failing test, and it will fail to compile because we haven’t yet defined
the search_case_insensitive
function. Feel free to add a skeleton
implementation that always returns an empty vector, similar to the way we did
for the search
function in Listing 12-16 to see the test compile and fail.
Implementing the search_case_insensitive
Function
The search_case_insensitive
function, shown in Listing 12-21, will be almost
the same as the search
function. The only difference is that we’ll lowercase
the query
and each line
so whatever the case of the input arguments,
they’ll be the same case when we check whether the line contains the query.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
for line in search(&config.query, &contents) {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
First, we lowercase the query
string and store it in a shadowed variable with
the same name. Calling to_lowercase
on the query is necessary so no
matter whether the user’s query is "rust"
, "RUST"
, "Rust"
, or "rUsT"
,
we’ll treat the query as if it were "rust"
and be insensitive to the case.
While to_lowercase
will handle basic Unicode, it won’t be 100% accurate. If
we were writing a real application, we’d want to do a bit more work here, but
this section is about environment variables, not Unicode, so we’ll leave it at
that here.
Note that query
is now a String
rather than a string slice, because calling
to_lowercase
creates new data rather than referencing existing data. Say the
query is "rUsT"
, as an example: that string slice doesn’t contain a lowercase
u
or t
for us to use, so we have to allocate a new String
containing
"rust"
. When we pass query
as an argument to the contains
method now, we
need to add an ampersand because the signature of contains
is defined to take
a string slice.
Next, we add a call to to_lowercase
on each line
to lowercase all
characters. Now that we’ve converted line
and query
to lowercase, we’ll
find matches no matter what the case of the query is.
Let’s see if this implementation passes the tests:
$ cargo test
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished test [unoptimized + debuginfo] target(s) in 1.33s
Running unittests src/lib.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 2 tests
test tests::case_insensitive ... ok
test tests::case_sensitive ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/minigrep-9cd200e5fac0fc94)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests minigrep
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Great! They passed. Now, let’s call the new search_case_insensitive
function
from the run
function. First, we’ll add a configuration option to the
Config
struct to switch between case-sensitive and case-insensitive search.
Adding this field will cause compiler errors because we aren’t initializing
this field anywhere yet:
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
We added the ignore_case
field that holds a Boolean. Next, we need the run
function to check the ignore_case
field’s value and use that to decide
whether to call the search
function or the search_case_insensitive
function, as shown in Listing 12-22. This still won’t compile yet.
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
Finally, we need to check for the environment variable. The functions for
working with environment variables are in the env
module in the standard
library, so we bring that module into scope at the top of src/lib.rs. Then
we’ll use the var
function from the env
module to check to see if any value
has been set for an environment variable named IGNORE_CASE
, as shown in
Listing 12-23.
Filename: src/lib.rs
use std::env;
// --snip--
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
Here, we create a new variable ignore_case
. To set its value, we call the
env::var
function and pass it the name of the IGNORE_CASE
environment
variable. The env::var
function returns a Result
that will be the
successful Ok
variant that contains the value of the environment variable if
the environment variable is set to any value. It will return the Err
variant
if the environment variable is not set.
We’re using the is_ok
method on the Result
to check whether the environment
variable is set, which means the program should do a case-insensitive search.
If the IGNORE_CASE
environment variable isn’t set to anything, is_ok
will
return false and the program will perform a case-sensitive search. We don’t
care about the value of the environment variable, just whether it’s set or
unset, so we’re checking is_ok
rather than using unwrap
, expect
, or any
of the other methods we’ve seen on Result
.
We pass the value in the ignore_case
variable to the Config
instance so the
run
function can read that value and decide whether to call
search_case_insensitive
or search
, as we implemented in Listing 12-22.
Let’s give it a try! First, we’ll run our program without the environment
variable set and with the query to
, which should match any line that contains
the word “to” in all lowercase:
$ cargo run -- to poem.txt
Compiling minigrep v0.1.0 (file:///projects/minigrep)
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/minigrep to poem.txt`
Are you nobody, too?
How dreary to be somebody!
Looks like that still works! Now, let’s run the program with IGNORE_CASE
set to 1
but with the same query to
.
$ IGNORE_CASE=1 cargo run -- to poem.txt
If you’re using PowerShell, you will need to set the environment variable and run the program as separate commands:
PS> $Env:IGNORE_CASE=1; cargo run -- to poem.txt
This will make IGNORE_CASE
persist for the remainder of your shell
session. It can be unset with the Remove-Item
cmdlet:
PS> Remove-Item Env:IGNORE_CASE
We should get lines that contain “to” that might have uppercase letters:
Are you nobody, too?
How dreary to be somebody!
To tell your name the livelong day
To an admiring bog!
Excellent, we also got lines containing “To”! Our minigrep
program can now do
case-insensitive searching controlled by an environment variable. Now you know
how to manage options set using either command line arguments or environment
variables.
Some programs allow arguments and environment variables for the same configuration. In those cases, the programs decide that one or the other takes precedence. For another exercise on your own, try controlling case sensitivity through either a command line argument or an environment variable. Decide whether the command line argument or the environment variable should take precedence if the program is run with one set to case sensitive and one set to ignore case.
The std::env
module contains many more useful features for dealing with
environment variables: check out its documentation to see what is available.
Writing Error Messages to Standard Error Instead of Standard Output
At the moment, we’re writing all of our output to the terminal using the
println!
macro. In most terminals, there are two kinds of output: standard
output (stdout
) for general information and standard error (stderr
) for
error messages. This distinction enables users to choose to direct the
successful output of a program to a file but still print error messages to the
screen.
The println!
macro is only capable of printing to standard output, so we
have to use something else to print to standard error.
Checking Where Errors Are Written
First, let’s observe how the content printed by minigrep
is currently being
written to standard output, including any error messages we want to write to
standard error instead. We’ll do that by redirecting the standard output stream
to a file while intentionally causing an error. We won’t redirect the standard
error stream, so any content sent to standard error will continue to display on
the screen.
Command line programs are expected to send error messages to the standard error stream so we can still see error messages on the screen even if we redirect the standard output stream to a file. Our program is not currently well-behaved: we’re about to see that it saves the error message output to a file instead!
To demonstrate this behavior, we’ll run the program with >
and the file path,
output.txt, that we want to redirect the standard output stream to. We won’t
pass any arguments, which should cause an error:
$ cargo run > output.txt
The >
syntax tells the shell to write the contents of standard output to
output.txt instead of the screen. We didn’t see the error message we were
expecting printed to the screen, so that means it must have ended up in the
file. This is what output.txt contains:
Problem parsing arguments: not enough arguments
Yup, our error message is being printed to standard output. It’s much more useful for error messages like this to be printed to standard error so only data from a successful run ends up in the file. We’ll change that.
Printing Errors to Standard Error
We’ll use the code in Listing 12-24 to change how error messages are printed.
Because of the refactoring we did earlier in this chapter, all the code that
prints error messages is in one function, main
. The standard library provides
the eprintln!
macro that prints to the standard error stream, so let’s change
the two places we were calling println!
to print errors to use eprintln!
instead.
Filename: src/main.rs
use std::env;
use std::process;
use minigrep::Config;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
if let Err(e) = minigrep::run(config) {
eprintln!("Application error: {e}");
process::exit(1);
}
}
Let’s now run the program again in the same way, without any arguments and
redirecting standard output with >
:
$ cargo run > output.txt
Problem parsing arguments: not enough arguments
Now we see the error onscreen and output.txt contains nothing, which is the behavior we expect of command line programs.
Let’s run the program again with arguments that don’t cause an error but still redirect standard output to a file, like so:
$ cargo run -- to poem.txt > output.txt
We won’t see any output to the terminal, and output.txt will contain our results:
Filename: output.txt
Are you nobody, too?
How dreary to be somebody!
This demonstrates that we’re now using standard output for successful output and standard error for error output as appropriate.
Summary
This chapter recapped some of the major concepts you’ve learned so far and
covered how to perform common I/O operations in Rust. By using command line
arguments, files, environment variables, and the eprintln!
macro for printing
errors, you’re now prepared to write command line applications. Combined with
the concepts in previous chapters, your code will be well organized, store data
effectively in the appropriate data structures, handle errors nicely, and be
well tested.
Next, we’ll explore some Rust features that were influenced by functional languages: closures and iterators.
Functional Language Features: Iterators and Closures
Rust’s design has taken inspiration from many existing languages and techniques, and one significant influence is functional programming. Programming in a functional style often includes using functions as values by passing them in arguments, returning them from other functions, assigning them to variables for later execution, and so forth.
In this chapter, we won’t debate the issue of what functional programming is or isn’t but will instead discuss some features of Rust that are similar to features in many languages often referred to as functional.
More specifically, we’ll cover:
- Closures, a function-like construct you can store in a variable
- Iterators, a way of processing a series of elements
- How to use closures and iterators to improve the I/O project in Chapter 12
- The performance of closures and iterators (Spoiler alert: they’re faster than you might think!)
We’ve already covered some other Rust features, such as pattern matching and enums, that are also influenced by the functional style. Because mastering closures and iterators is an important part of writing idiomatic, fast Rust code, we’ll devote this entire chapter to them.
Closures: Anonymous Functions that Capture Their Environment
Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they’re defined. We’ll demonstrate how these closure features allow for code reuse and behavior customization.
Capturing the Environment with Closures
We’ll first examine how we can use closures to capture values from the environment they’re defined in for later use. Here’s the scenario: Every so often, our t-shirt company gives away an exclusive, limited-edition shirt to someone on our mailing list as a promotion. People on the mailing list can optionally add their favorite color to their profile. If the person chosen for a free shirt has their favorite color set, they get that color shirt. If the person hasn’t specified a favorite color, they get whatever color the company currently has the most of.
There are many ways to implement this. For this example, we’re going to use an
enum called ShirtColor
that has the variants Red
and Blue
(limiting the
number of colors available for simplicity). We represent the company’s
inventory with an Inventory
struct that has a field named shirts
that
contains a Vec<ShirtColor>
representing the shirt colors currently in stock.
The method giveaway
defined on Inventory
gets the optional shirt
color preference of the free shirt winner, and returns the shirt color the
person will get. This setup is shown in Listing 13-1:
Filename: src/main.rs
#[derive(Debug, PartialEq, Copy, Clone)]
enum ShirtColor {
Red,
Blue,
}
struct Inventory {
shirts: Vec<ShirtColor>,
}
impl Inventory {
fn giveaway(&self, user_preference: Option<ShirtColor>) -> ShirtColor {
user_preference.unwrap_or_else(|| self.most_stocked())
}
fn most_stocked(&self) -> ShirtColor {
let mut num_red = 0;
let mut num_blue = 0;
for color in &self.shirts {
match color {
ShirtColor::Red => num_red += 1,
ShirtColor::Blue => num_blue += 1,
}
}
if num_red > num_blue {
ShirtColor::Red
} else {
ShirtColor::Blue
}
}
}
fn main() {
let store = Inventory {
shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue],
};
let user_pref1 = Some(ShirtColor::Red);
let giveaway1 = store.giveaway(user_pref1);
println!(
"The user with preference {:?} gets {:?}",
user_pref1, giveaway1
);
let user_pref2 = None;
let giveaway2 = store.giveaway(user_pref2);
println!(
"The user with preference {:?} gets {:?}",
user_pref2, giveaway2
);
}
The store
defined in main
has two blue shirts and one red shirt remaining
to distribute for this limited-edition promotion. We call the giveaway
method
for a user with a preference for a red shirt and a user without any preference.
Again, this code could be implemented in many ways, and here, to focus on
closures, we’ve stuck to concepts you’ve already learned except for the body of
the giveaway
method that uses a closure. In the giveaway
method, we get the
user preference as a parameter of type Option<ShirtColor>
and call the
unwrap_or_else
method on user_preference
. The unwrap_or_else
method on
Option<T>
is defined by the standard library.
It takes one argument: a closure without any arguments that returns a value T
(the same type stored in the Some
variant of the Option<T>
, in this case
ShirtColor
). If the Option<T>
is the Some
variant, unwrap_or_else
returns the value from within the Some
. If the Option<T>
is the None
variant, unwrap_or_else
calls the closure and returns the value returned by
the closure.
We specify the closure expression || self.most_stocked()
as the argument to
unwrap_or_else
. This is a closure that takes no parameters itself (if the
closure had parameters, they would appear between the two vertical bars). The
body of the closure calls self.most_stocked()
. We’re defining the closure
here, and the implementation of unwrap_or_else
will evaluate the closure
later if the result is needed.
Running this code prints:
$ cargo run
Compiling shirt-company v0.1.0 (file:///projects/shirt-company)
Finished dev [unoptimized + debuginfo] target(s) in 0.27s
Running `target/debug/shirt-company`
The user with preference Some(Red) gets Red
The user with preference None gets Blue
One interesting aspect here is that we’ve passed a closure that calls
self.most_stocked()
on the current Inventory
instance. The standard library
didn’t need to know anything about the Inventory
or ShirtColor
types we
defined, or the logic we want to use in this scenario. The closure captures an
immutable reference to the self
Inventory
instance and passes it with the
code we specify to the unwrap_or_else
method. Functions, on the other hand,
are not able to capture their environment in this way.
Closure Type Inference and Annotation
There are more differences between functions and closures. Closures don’t
usually require you to annotate the types of the parameters or the return value
like fn
functions do. Type annotations are required on functions because the
types are part of an explicit interface exposed to your users. Defining this
interface rigidly is important for ensuring that everyone agrees on what types
of values a function uses and returns. Closures, on the other hand, aren’t used
in an exposed interface like this: they’re stored in variables and used without
naming them and exposing them to users of our library.
Closures are typically short and relevant only within a narrow context rather than in any arbitrary scenario. Within these limited contexts, the compiler can infer the types of the parameters and the return type, similar to how it’s able to infer the types of most variables (there are rare cases where the compiler needs closure type annotations too).
As with variables, we can add type annotations if we want to increase explicitness and clarity at the cost of being more verbose than is strictly necessary. Annotating the types for a closure would look like the definition shown in Listing 13-2. In this example, we’re defining a closure and storing it in a variable rather than defining the closure in the spot we pass it as an argument as we did in Listing 13-1.
Filename: src/main.rs
use std::thread; use std::time::Duration; fn generate_workout(intensity: u32, random_number: u32) { let expensive_closure = |num: u32| -> u32 { println!("calculating slowly..."); thread::sleep(Duration::from_secs(2)); num }; if intensity < 25 { println!("Today, do {} pushups!", expensive_closure(intensity)); println!("Next, do {} situps!", expensive_closure(intensity)); } else { if random_number == 3 { println!("Take a break today! Remember to stay hydrated!"); } else { println!( "Today, run for {} minutes!", expensive_closure(intensity) ); } } } fn main() { let simulated_user_specified_value = 10; let simulated_random_number = 7; generate_workout(simulated_user_specified_value, simulated_random_number); }
With type annotations added, the syntax of closures looks more similar to the syntax of functions. Here we define a function that adds 1 to its parameter and a closure that has the same behavior, for comparison. We’ve added some spaces to line up the relevant parts. This illustrates how closure syntax is similar to function syntax except for the use of pipes and the amount of syntax that is optional:
fn add_one_v1 (x: u32) -> u32 { x + 1 }
let add_one_v2 = |x: u32| -> u32 { x + 1 };
let add_one_v3 = |x| { x + 1 };
let add_one_v4 = |x| x + 1 ;
The first line shows a function definition, and the second line shows a fully
annotated closure definition. In the third line, we remove the type annotations
from the closure definition. In the fourth line, we remove the brackets, which
are optional because the closure body has only one expression. These are all
valid definitions that will produce the same behavior when they’re called. The
add_one_v3
and add_one_v4
lines require the closures to be evaluated to be
able to compile because the types will be inferred from their usage. This is
similar to let v = Vec::new();
needing either type annotations or values of
some type to be inserted into the Vec
for Rust to be able to infer the type.
For closure definitions, the compiler will infer one concrete type for each of
their parameters and for their return value. For instance, Listing 13-3 shows
the definition of a short closure that just returns the value it receives as a
parameter. This closure isn’t very useful except for the purposes of this
example. Note that we haven’t added any type annotations to the definition.
Because there are no type annotations, we can call the closure with any type,
which we’ve done here with String
the first time. If we then try to call
example_closure
with an integer, we’ll get an error.
Filename: src/main.rs
fn main() {
let example_closure = |x| x;
let s = example_closure(String::from("hello"));
let n = example_closure(5);
}
The compiler gives us this error:
$ cargo run
Compiling closure-example v0.1.0 (file:///projects/closure-example)
error[E0308]: mismatched types
--> src/main.rs:5:29
|
5 | let n = example_closure(5);
| --------------- ^- help: try using a conversion method: `.to_string()`
| | |
| | expected struct `String`, found integer
| arguments to this function are incorrect
|
note: closure parameter defined here
--> src/main.rs:2:28
|
2 | let example_closure = |x| x;
| ^
For more information about this error, try `rustc --explain E0308`.
error: could not compile `closure-example` due to previous error
The first time we call example_closure
with the String
value, the compiler
infers the type of x
and the return type of the closure to be String
. Those
types are then locked into the closure in example_closure
, and we get a type
error when we next try to use a different type with the same closure.
Capturing References or Moving Ownership
Closures can capture values from their environment in three ways, which directly map to the three ways a function can take a parameter: borrowing immutably, borrowing mutably, and taking ownership. The closure will decide which of these to use based on what the body of the function does with the captured values.
In Listing 13-4, we define a closure that captures an immutable reference to
the vector named list
because it only needs an immutable reference to print
the value:
Filename: src/main.rs
fn main() { let list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); let only_borrows = || println!("From closure: {:?}", list); println!("Before calling closure: {:?}", list); only_borrows(); println!("After calling closure: {:?}", list); }
This example also illustrates that a variable can bind to a closure definition, and we can later call the closure by using the variable name and parentheses as if the variable name were a function name.
Because we can have multiple immutable references to list
at the same time,
list
is still accessible from the code before the closure definition, after
the closure definition but before the closure is called, and after the closure
is called. This code compiles, runs, and prints:
$ cargo run
Compiling closure-example v0.1.0 (file:///projects/closure-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/closure-example`
Before defining closure: [1, 2, 3]
Before calling closure: [1, 2, 3]
From closure: [1, 2, 3]
After calling closure: [1, 2, 3]
Next, in Listing 13-5, we change the closure body so that it adds an element to
the list
vector. The closure now captures a mutable reference:
Filename: src/main.rs
fn main() { let mut list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); let mut borrows_mutably = || list.push(7); borrows_mutably(); println!("After calling closure: {:?}", list); }
This code compiles, runs, and prints:
$ cargo run
Compiling closure-example v0.1.0 (file:///projects/closure-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/closure-example`
Before defining closure: [1, 2, 3]
After calling closure: [1, 2, 3, 7]
Note that there’s no longer a println!
between the definition and the call of
the borrows_mutably
closure: when borrows_mutably
is defined, it captures a
mutable reference to list
. We don’t use the closure again after the closure
is called, so the mutable borrow ends. Between the closure definition and the
closure call, an immutable borrow to print isn’t allowed because no other
borrows are allowed when there’s a mutable borrow. Try adding a println!
there to see what error message you get!
If you want to force the closure to take ownership of the values it uses in the
environment even though the body of the closure doesn’t strictly need
ownership, you can use the move
keyword before the parameter list.
This technique is mostly useful when passing a closure to a new thread to move
the data so that it’s owned by the new thread. We’ll discuss threads and why
you would want to use them in detail in Chapter 16 when we talk about
concurrency, but for now, let’s briefly explore spawning a new thread using a
closure that needs the move
keyword. Listing 13-6 shows Listing 13-4 modified
to print the vector in a new thread rather than in the main thread:
Filename: src/main.rs
use std::thread; fn main() { let list = vec![1, 2, 3]; println!("Before defining closure: {:?}", list); thread::spawn(move || println!("From thread: {:?}", list)) .join() .unwrap(); }
We spawn a new thread, giving the thread a closure to run as an argument. The
closure body prints out the list. In Listing 13-4, the closure only captured
list
using an immutable reference because that's the least amount of access
to list
needed to print it. In this example, even though the closure body
still only needs an immutable reference, we need to specify that list
should
be moved into the closure by putting the move
keyword at the beginning of the
closure definition. The new thread might finish before the rest of the main
thread finishes, or the main thread might finish first. If the main thread
maintained ownership of list
but ended before the new thread did and dropped
list
, the immutable reference in the thread would be invalid. Therefore, the
compiler requires that list
be moved into the closure given to the new thread
so the reference will be valid. Try removing the move
keyword or using list
in the main thread after the closure is defined to see what compiler errors you
get!
Moving Captured Values Out of Closures and the Fn
Traits
Once a closure has captured a reference or captured ownership of a value from the environment where the closure is defined (thus affecting what, if anything, is moved into the closure), the code in the body of the closure defines what happens to the references or values when the closure is evaluated later (thus affecting what, if anything, is moved out of the closure). A closure body can do any of the following: move a captured value out of the closure, mutate the captured value, neither move nor mutate the value, or capture nothing from the environment to begin with.
The way a closure captures and handles values from the environment affects
which traits the closure implements, and traits are how functions and structs
can specify what kinds of closures they can use. Closures will automatically
implement one, two, or all three of these Fn
traits, in an additive fashion,
depending on how the closure’s body handles the values:
FnOnce
applies to closures that can be called once. All closures implement at least this trait, because all closures can be called. A closure that moves captured values out of its body will only implementFnOnce
and none of the otherFn
traits, because it can only be called once.FnMut
applies to closures that don’t move captured values out of their body, but that might mutate the captured values. These closures can be called more than once.Fn
applies to closures that don’t move captured values out of their body and that don’t mutate captured values, as well as closures that capture nothing from their environment. These closures can be called more than once without mutating their environment, which is important in cases such as calling a closure multiple times concurrently.
Let’s look at the definition of the unwrap_or_else
method on Option<T>
that
we used in Listing 13-1:
impl<T> Option<T> {
pub fn unwrap_or_else<F>(self, f: F) -> T
where
F: FnOnce() -> T
{
match self {
Some(x) => x,
None => f(),
}
}
}
Recall that T
is the generic type representing the type of the value in the
Some
variant of an Option
. That type T
is also the return type of the
unwrap_or_else
function: code that calls unwrap_or_else
on an
Option<String>
, for example, will get a String
.
Next, notice that the unwrap_or_else
function has the additional generic type
parameter F
. The F
type is the type of the parameter named f
, which is
the closure we provide when calling unwrap_or_else
.
The trait bound specified on the generic type F
is FnOnce() -> T
, which
means F
must be able to be called once, take no arguments, and return a T
.
Using FnOnce
in the trait bound expresses the constraint that
unwrap_or_else
is only going to call f
at most one time. In the body of
unwrap_or_else
, we can see that if the Option
is Some
, f
won’t be
called. If the Option
is None
, f
will be called once. Because all
closures implement FnOnce
, unwrap_or_else
accepts the most different kinds
of closures and is as flexible as it can be.
Note: Functions can implement all three of the
Fn
traits too. If what we want to do doesn’t require capturing a value from the environment, we can use the name of a function rather than a closure where we need something that implements one of theFn
traits. For example, on anOption<Vec<T>>
value, we could callunwrap_or_else(Vec::new)
to get a new, empty vector if the value isNone
.
Now let’s look at the standard library method sort_by_key
defined on slices,
to see how that differs from unwrap_or_else
and why sort_by_key
uses
FnMut
instead of FnOnce
for the trait bound. The closure gets one argument
in the form of a reference to the current item in the slice being considered,
and returns a value of type K
that can be ordered. This function is useful
when you want to sort a slice by a particular attribute of each item. In
Listing 13-7, we have a list of Rectangle
instances and we use sort_by_key
to order them by their width
attribute from low to high:
Filename: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [ Rectangle { width: 10, height: 1 }, Rectangle { width: 3, height: 5 }, Rectangle { width: 7, height: 12 }, ]; list.sort_by_key(|r| r.width); println!("{:#?}", list); }
This code prints:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
Finished dev [unoptimized + debuginfo] target(s) in 0.41s
Running `target/debug/rectangles`
[
Rectangle {
width: 3,
height: 5,
},
Rectangle {
width: 7,
height: 12,
},
Rectangle {
width: 10,
height: 1,
},
]
The reason sort_by_key
is defined to take an FnMut
closure is that it calls
the closure multiple times: once for each item in the slice. The closure |r| r.width
doesn’t capture, mutate, or move out anything from its environment, so
it meets the trait bound requirements.
In contrast, Listing 13-8 shows an example of a closure that implements just
the FnOnce
trait, because it moves a value out of the environment. The
compiler won’t let us use this closure with sort_by_key
:
Filename: src/main.rs
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
fn main() {
let mut list = [
Rectangle { width: 10, height: 1 },
Rectangle { width: 3, height: 5 },
Rectangle { width: 7, height: 12 },
];
let mut sort_operations = vec![];
let value = String::from("by key called");
list.sort_by_key(|r| {
sort_operations.push(value);
r.width
});
println!("{:#?}", list);
}
This is a contrived, convoluted way (that doesn’t work) to try and count the
number of times sort_by_key
gets called when sorting list
. This code
attempts to do this counting by pushing value
—a String
from the closure’s
environment—into the sort_operations
vector. The closure captures value
then moves value
out of the closure by transferring ownership of value
to
the sort_operations
vector. This closure can be called once; trying to call
it a second time wouldn’t work because value
would no longer be in the
environment to be pushed into sort_operations
again! Therefore, this closure
only implements FnOnce
. When we try to compile this code, we get this error
that value
can’t be moved out of the closure because the closure must
implement FnMut
:
$ cargo run
Compiling rectangles v0.1.0 (file:///projects/rectangles)
error[E0507]: cannot move out of `value`, a captured variable in an `FnMut` closure
--> src/main.rs:18:30
|
15 | let value = String::from("by key called");
| ----- captured outer variable
16 |
17 | list.sort_by_key(|r| {
| --- captured by this `FnMut` closure
18 | sort_operations.push(value);
| ^^^^^ move occurs because `value` has type `String`, which does not implement the `Copy` trait
For more information about this error, try `rustc --explain E0507`.
error: could not compile `rectangles` due to previous error
The error points to the line in the closure body that moves value
out of the
environment. To fix this, we need to change the closure body so that it doesn’t
move values out of the environment. To count the number of times sort_by_key
is called, keeping a counter in the environment and incrementing its value in
the closure body is a more straightforward way to calculate that. The closure
in Listing 13-9 works with sort_by_key
because it is only capturing a mutable
reference to the num_sort_operations
counter and can therefore be called more
than once:
Filename: src/main.rs
#[derive(Debug)] struct Rectangle { width: u32, height: u32, } fn main() { let mut list = [ Rectangle { width: 10, height: 1 }, Rectangle { width: 3, height: 5 }, Rectangle { width: 7, height: 12 }, ]; let mut num_sort_operations = 0; list.sort_by_key(|r| { num_sort_operations += 1; r.width }); println!("{:#?}, sorted in {num_sort_operations} operations", list); }
The Fn
traits are important when defining or using functions or types that
make use of closures. In the next section, we’ll discuss iterators. Many
iterator methods take closure arguments, so keep these closure details in mind
as we continue!
Processing a Series of Items with Iterators
The iterator pattern allows you to perform some task on a sequence of items in turn. An iterator is responsible for the logic of iterating over each item and determining when the sequence has finished. When you use iterators, you don’t have to reimplement that logic yourself.
In Rust, iterators are lazy, meaning they have no effect until you call
methods that consume the iterator to use it up. For example, the code in
Listing 13-10 creates an iterator over the items in the vector v1
by calling
the iter
method defined on Vec<T>
. This code by itself doesn’t do anything
useful.
fn main() { let v1 = vec![1, 2, 3]; let v1_iter = v1.iter(); }
The iterator is stored in the v1_iter
variable. Once we’ve created an
iterator, we can use it in a variety of ways. In Listing 3-5 in Chapter 3, we
iterated over an array using a for
loop to execute some code on each of its
items. Under the hood this implicitly created and then consumed an iterator,
but we glossed over how exactly that works until now.
In the example in Listing 13-11, we separate the creation of the iterator from
the use of the iterator in the for
loop. When the for
loop is called using
the iterator in v1_iter
, each element in the iterator is used in one
iteration of the loop, which prints out each value.
fn main() { let v1 = vec![1, 2, 3]; let v1_iter = v1.iter(); for val in v1_iter { println!("Got: {}", val); } }
In languages that don’t have iterators provided by their standard libraries, you would likely write this same functionality by starting a variable at index 0, using that variable to index into the vector to get a value, and incrementing the variable value in a loop until it reached the total number of items in the vector.
Iterators handle all that logic for you, cutting down on repetitive code you could potentially mess up. Iterators give you more flexibility to use the same logic with many different kinds of sequences, not just data structures you can index into, like vectors. Let’s examine how iterators do that.
The Iterator
Trait and the next
Method
All iterators implement a trait named Iterator
that is defined in the
standard library. The definition of the trait looks like this:
#![allow(unused)] fn main() { pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; // methods with default implementations elided } }
Notice this definition uses some new syntax: type Item
and Self::Item
,
which are defining an associated type with this trait. We’ll talk about
associated types in depth in Chapter 19. For now, all you need to know is that
this code says implementing the Iterator
trait requires that you also define
an Item
type, and this Item
type is used in the return type of the next
method. In other words, the Item
type will be the type returned from the
iterator.
The Iterator
trait only requires implementors to define one method: the
next
method, which returns one item of the iterator at a time wrapped in
Some
and, when iteration is over, returns None
.
We can call the next
method on iterators directly; Listing 13-12 demonstrates
what values are returned from repeated calls to next
on the iterator created
from the vector.
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn iterator_demonstration() {
let v1 = vec![1, 2, 3];
let mut v1_iter = v1.iter();
assert_eq!(v1_iter.next(), Some(&1));
assert_eq!(v1_iter.next(), Some(&2));
assert_eq!(v1_iter.next(), Some(&3));
assert_eq!(v1_iter.next(), None);
}
}
Note that we needed to make v1_iter
mutable: calling the next
method on an
iterator changes internal state that the iterator uses to keep track of where
it is in the sequence. In other words, this code consumes, or uses up, the
iterator. Each call to next
eats up an item from the iterator. We didn’t need
to make v1_iter
mutable when we used a for
loop because the loop took
ownership of v1_iter
and made it mutable behind the scenes.
Also note that the values we get from the calls to next
are immutable
references to the values in the vector. The iter
method produces an iterator
over immutable references. If we want to create an iterator that takes
ownership of v1
and returns owned values, we can call into_iter
instead of
iter
. Similarly, if we want to iterate over mutable references, we can call
iter_mut
instead of iter
.
Methods that Consume the Iterator
The Iterator
trait has a number of different methods with default
implementations provided by the standard library; you can find out about these
methods by looking in the standard library API documentation for the Iterator
trait. Some of these methods call the next
method in their definition, which
is why you’re required to implement the next
method when implementing the
Iterator
trait.
Methods that call next
are called consuming adaptors, because calling them
uses up the iterator. One example is the sum
method, which takes ownership of
the iterator and iterates through the items by repeatedly calling next
, thus
consuming the iterator. As it iterates through, it adds each item to a running
total and returns the total when iteration is complete. Listing 13-13 has a
test illustrating a use of the sum
method:
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
fn iterator_sum() {
let v1 = vec![1, 2, 3];
let v1_iter = v1.iter();
let total: i32 = v1_iter.sum();
assert_eq!(total, 6);
}
}
We aren’t allowed to use v1_iter
after the call to sum
because sum
takes
ownership of the iterator we call it on.
Methods that Produce Other Iterators
Iterator adaptors are methods defined on the Iterator
trait that don’t
consume the iterator. Instead, they produce different iterators by changing
some aspect of the original iterator.
Listing 13-14 shows an example of calling the iterator adaptor method map
,
which takes a closure to call on each item as the items are iterated through.
The map
method returns a new iterator that produces the modified items. The
closure here creates a new iterator in which each item from the vector will be
incremented by 1:
Filename: src/main.rs
fn main() { let v1: Vec<i32> = vec![1, 2, 3]; v1.iter().map(|x| x + 1); }
However, this code produces a warning:
$ cargo run
Compiling iterators v0.1.0 (file:///projects/iterators)
warning: unused `Map` that must be used
--> src/main.rs:4:5
|
4 | v1.iter().map(|x| x + 1);
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
= note: iterators are lazy and do nothing unless consumed
= note: `#[warn(unused_must_use)]` on by default
warning: `iterators` (bin "iterators") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.47s
Running `target/debug/iterators`
The code in Listing 13-14 doesn’t do anything; the closure we’ve specified never gets called. The warning reminds us why: iterator adaptors are lazy, and we need to consume the iterator here.
To fix this warning and consume the iterator, we’ll use the collect
method,
which we used in Chapter 12 with env::args
in Listing 12-1. This method
consumes the iterator and collects the resulting values into a collection data
type.
In Listing 13-15, we collect the results of iterating over the iterator that’s
returned from the call to map
into a vector. This vector will end up
containing each item from the original vector incremented by 1.
Filename: src/main.rs
fn main() { let v1: Vec<i32> = vec![1, 2, 3]; let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); assert_eq!(v2, vec![2, 3, 4]); }
Because map
takes a closure, we can specify any operation we want to perform
on each item. This is a great example of how closures let you customize some
behavior while reusing the iteration behavior that the Iterator
trait
provides.
You can chain multiple calls to iterator adaptors to perform complex actions in a readable way. But because all iterators are lazy, you have to call one of the consuming adaptor methods to get results from calls to iterator adaptors.
Using Closures that Capture Their Environment
Many iterator adapters take closures as arguments, and commonly the closures we’ll specify as arguments to iterator adapters will be closures that capture their environment.
For this example, we’ll use the filter
method that takes a closure. The
closure gets an item from the iterator and returns a bool
. If the closure
returns true
, the value will be included in the iteration produced by
filter
. If the closure returns false
, the value won’t be included.
In Listing 13-16, we use filter
with a closure that captures the shoe_size
variable from its environment to iterate over a collection of Shoe
struct
instances. It will return only shoes that are the specified size.
Filename: src/lib.rs
#[derive(PartialEq, Debug)]
struct Shoe {
size: u32,
style: String,
}
fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn filters_by_size() {
let shoes = vec![
Shoe {
size: 10,
style: String::from("sneaker"),
},
Shoe {
size: 13,
style: String::from("sandal"),
},
Shoe {
size: 10,
style: String::from("boot"),
},
];
let in_my_size = shoes_in_size(shoes, 10);
assert_eq!(
in_my_size,
vec![
Shoe {
size: 10,
style: String::from("sneaker")
},
Shoe {
size: 10,
style: String::from("boot")
},
]
);
}
}
The shoes_in_size
function takes ownership of a vector of shoes and a shoe
size as parameters. It returns a vector containing only shoes of the specified
size.
In the body of shoes_in_size
, we call into_iter
to create an iterator
that takes ownership of the vector. Then we call filter
to adapt that
iterator into a new iterator that only contains elements for which the closure
returns true
.
The closure captures the shoe_size
parameter from the environment and
compares the value with each shoe’s size, keeping only shoes of the size
specified. Finally, calling collect
gathers the values returned by the
adapted iterator into a vector that’s returned by the function.
The test shows that when we call shoes_in_size
, we get back only shoes
that have the same size as the value we specified.
Improving Our I/O Project
With this new knowledge about iterators, we can improve the I/O project in
Chapter 12 by using iterators to make places in the code clearer and more
concise. Let’s look at how iterators can improve our implementation of the
Config::build
function and the search
function.
Removing a clone
Using an Iterator
In Listing 12-6, we added code that took a slice of String
values and created
an instance of the Config
struct by indexing into the slice and cloning the
values, allowing the Config
struct to own those values. In Listing 13-17,
we’ve reproduced the implementation of the Config::build
function as it was
in Listing 12-23:
Filename: src/lib.rs
use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
At the time, we said not to worry about the inefficient clone
calls because
we would remove them in the future. Well, that time is now!
We needed clone
here because we have a slice with String
elements in the
parameter args
, but the build
function doesn’t own args
. To return
ownership of a Config
instance, we had to clone the values from the query
and file_path
fields of Config
so the Config
instance can own its values.
With our new knowledge about iterators, we can change the build
function to
take ownership of an iterator as its argument instead of borrowing a slice.
We’ll use the iterator functionality instead of the code that checks the length
of the slice and indexes into specific locations. This will clarify what the
Config::build
function is doing because the iterator will access the values.
Once Config::build
takes ownership of the iterator and stops using indexing
operations that borrow, we can move the String
values from the iterator into
Config
rather than calling clone
and making a new allocation.
Using the Returned Iterator Directly
Open your I/O project’s src/main.rs file, which should look like this:
Filename: src/main.rs
use std::env;
use std::process;
use minigrep::Config;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::build(&args).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
// --snip--
if let Err(e) = minigrep::run(config) {
eprintln!("Application error: {e}");
process::exit(1);
}
}
We’ll first change the start of the main
function that we had in Listing
12-24 to the code in Listing 13-18, which this time uses an iterator. This
won’t compile until we update Config::build
as well.
Filename: src/main.rs
use std::env;
use std::process;
use minigrep::Config;
fn main() {
let config = Config::build(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {err}");
process::exit(1);
});
// --snip--
if let Err(e) = minigrep::run(config) {
eprintln!("Application error: {e}");
process::exit(1);
}
}
The env::args
function returns an iterator! Rather than collecting the
iterator values into a vector and then passing a slice to Config::build
, now
we’re passing ownership of the iterator returned from env::args
to
Config::build
directly.
Next, we need to update the definition of Config::build
. In your I/O
project’s src/lib.rs file, let’s change the signature of Config::build
to
look like Listing 13-19. This still won’t compile because we need to update the
function body.
Filename: src/lib.rs
use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(
mut args: impl Iterator<Item = String>,
) -> Result<Config, &'static str> {
// --snip--
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
The standard library documentation for the env::args
function shows that the
type of the iterator it returns is std::env::Args
, and that type implements
the Iterator
trait and returns String
values.
We’ve updated the signature of the Config::build
function so the parameter
args
has a generic type with the trait bounds impl Iterator<Item = String>
instead of &[String]
. This usage of the impl Trait
syntax we discussed in
the “Traits as Parameters” section of Chapter 10
means that args
can be any type that implements the Iterator
type and
returns String
items.
Because we’re taking ownership of args
and we’ll be mutating args
by
iterating over it, we can add the mut
keyword into the specification of the
args
parameter to make it mutable.
Using Iterator
Trait Methods Instead of Indexing
Next, we’ll fix the body of Config::build
. Because args
implements the
Iterator
trait, we know we can call the next
method on it! Listing 13-20
updates the code from Listing 12-23 to use the next
method:
Filename: src/lib.rs
use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(
mut args: impl Iterator<Item = String>,
) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string"),
};
let file_path = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file path"),
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
Remember that the first value in the return value of env::args
is the name of
the program. We want to ignore that and get to the next value, so first we call
next
and do nothing with the return value. Second, we call next
to get the
value we want to put in the query
field of Config
. If next
returns a
Some
, we use a match
to extract the value. If it returns None
, it means
not enough arguments were given and we return early with an Err
value. We do
the same thing for the file_path
value.
Making Code Clearer with Iterator Adaptors
We can also take advantage of iterators in the search
function in our I/O
project, which is reproduced here in Listing 13-21 as it was in Listing 12-19:
Filename: src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("not enough arguments");
}
let query = args[1].clone();
let file_path = args[2].clone();
Ok(Config { query, file_path })
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
let mut results = Vec::new();
for line in contents.lines() {
if line.contains(query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn one_result() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
}
We can write this code in a more concise way using iterator adaptor methods.
Doing so also lets us avoid having a mutable intermediate results
vector. The
functional programming style prefers to minimize the amount of mutable state to
make code clearer. Removing the mutable state might enable a future enhancement
to make searching happen in parallel, because we wouldn’t have to manage
concurrent access to the results
vector. Listing 13-22 shows this change:
Filename: src/lib.rs
use std::env;
use std::error::Error;
use std::fs;
pub struct Config {
pub query: String,
pub file_path: String,
pub ignore_case: bool,
}
impl Config {
pub fn build(
mut args: impl Iterator<Item = String>,
) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string"),
};
let file_path = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file path"),
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config {
query,
file_path,
ignore_case,
})
}
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.file_path)?;
let results = if config.ignore_case {
search_case_insensitive(&config.query, &contents)
} else {
search(&config.query, &contents)
};
for line in results {
println!("{line}");
}
Ok(())
}
pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
contents
.lines()
.filter(|line| line.contains(query))
.collect()
}
pub fn search_case_insensitive<'a>(
query: &str,
contents: &'a str,
) -> Vec<&'a str> {
let query = query.to_lowercase();
let mut results = Vec::new();
for line in contents.lines() {
if line.to_lowercase().contains(&query) {
results.push(line);
}
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn case_sensitive() {
let query = "duct";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Duct tape.";
assert_eq!(vec!["safe, fast, productive."], search(query, contents));
}
#[test]
fn case_insensitive() {
let query = "rUsT";
let contents = "\
Rust:
safe, fast, productive.
Pick three.
Trust me.";
assert_eq!(
vec!["Rust:", "Trust me."],
search_case_insensitive(query, contents)
);
}
}
Recall that the purpose of the search
function is to return all lines in
contents
that contain the query
. Similar to the filter
example in Listing
13-16, this code uses the filter
adaptor to keep only the lines that
line.contains(query)
returns true
for. We then collect the matching lines
into another vector with collect
. Much simpler! Feel free to make the same
change to use iterator methods in the search_case_insensitive
function as
well.
Choosing Between Loops or Iterators
The next logical question is which style you should choose in your own code and why: the original implementation in Listing 13-21 or the version using iterators in Listing 13-22. Most Rust programmers prefer to use the iterator style. It’s a bit tougher to get the hang of at first, but once you get a feel for the various iterator adaptors and what they do, iterators can be easier to understand. Instead of fiddling with the various bits of looping and building new vectors, the code focuses on the high-level objective of the loop. This abstracts away some of the commonplace code so it’s easier to see the concepts that are unique to this code, such as the filtering condition each element in the iterator must pass.
But are the two implementations truly equivalent? The intuitive assumption might be that the more low-level loop will be faster. Let’s talk about performance.
Comparing Performance: Loops vs. Iterators
To determine whether to use loops or iterators, you need to know which
implementation is faster: the version of the search
function with an explicit
for
loop or the version with iterators.
We ran a benchmark by loading the entire contents of The Adventures of
Sherlock Holmes by Sir Arthur Conan Doyle into a String
and looking for the
word the in the contents. Here are the results of the benchmark on the
version of search
using the for
loop and the version using iterators:
test bench_search_for ... bench: 19,620,300 ns/iter (+/- 915,700)
test bench_search_iter ... bench: 19,234,900 ns/iter (+/- 657,200)
The iterator version was slightly faster! We won’t explain the benchmark code here, because the point is not to prove that the two versions are equivalent but to get a general sense of how these two implementations compare performance-wise.
For a more comprehensive benchmark, you should check using various texts of
various sizes as the contents
, different words and words of different lengths
as the query
, and all kinds of other variations. The point is this:
iterators, although a high-level abstraction, get compiled down to roughly the
same code as if you’d written the lower-level code yourself. Iterators are one
of Rust’s zero-cost abstractions, by which we mean using the abstraction
imposes no additional runtime overhead. This is analogous to how Bjarne
Stroustrup, the original designer and implementor of C++, defines
zero-overhead in “Foundations of C++” (2012):
In general, C++ implementations obey the zero-overhead principle: What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better.
As another example, the following code is taken from an audio decoder. The
decoding algorithm uses the linear prediction mathematical operation to
estimate future values based on a linear function of the previous samples. This
code uses an iterator chain to do some math on three variables in scope: a
buffer
slice of data, an array of 12 coefficients
, and an amount by which
to shift data in qlp_shift
. We’ve declared the variables within this example
but not given them any values; although this code doesn’t have much meaning
outside of its context, it’s still a concise, real-world example of how Rust
translates high-level ideas to low-level code.
let buffer: &mut [i32];
let coefficients: [i64; 12];
let qlp_shift: i16;
for i in 12..buffer.len() {
let prediction = coefficients.iter()
.zip(&buffer[i - 12..i])
.map(|(&c, &s)| c * s as i64)
.sum::<i64>() >> qlp_shift;
let delta = buffer[i];
buffer[i] = prediction as i32 + delta;
}
To calculate the value of prediction
, this code iterates through each of the
12 values in coefficients
and uses the zip
method to pair the coefficient
values with the previous 12 values in buffer
. Then, for each pair, we
multiply the values together, sum all the results, and shift the bits in the
sum qlp_shift
bits to the right.
Calculations in applications like audio decoders often prioritize performance
most highly. Here, we’re creating an iterator, using two adaptors, and then
consuming the value. What assembly code would this Rust code compile to? Well,
as of this writing, it compiles down to the same assembly you’d write by hand.
There’s no loop at all corresponding to the iteration over the values in
coefficients
: Rust knows that there are 12 iterations, so it “unrolls” the
loop. Unrolling is an optimization that removes the overhead of the loop
controlling code and instead generates repetitive code for each iteration of
the loop.
All of the coefficients get stored in registers, which means accessing the values is very fast. There are no bounds checks on the array access at runtime. All these optimizations that Rust is able to apply make the resulting code extremely efficient. Now that you know this, you can use iterators and closures without fear! They make code seem like it’s higher level but don’t impose a runtime performance penalty for doing so.
Summary
Closures and iterators are Rust features inspired by functional programming language ideas. They contribute to Rust’s capability to clearly express high-level ideas at low-level performance. The implementations of closures and iterators are such that runtime performance is not affected. This is part of Rust’s goal to strive to provide zero-cost abstractions.
Now that we’ve improved the expressiveness of our I/O project, let’s look at
some more features of cargo
that will help us share the project with the
world.
More About Cargo and Crates.io
So far we’ve used only the most basic features of Cargo to build, run, and test our code, but it can do a lot more. In this chapter, we’ll discuss some of its other, more advanced features to show you how to do the following:
- Customize your build through release profiles
- Publish libraries on crates.io
- Organize large projects with workspaces
- Install binaries from crates.io
- Extend Cargo using custom commands
Cargo can do even more than the functionality we cover in this chapter, so for a full explanation of all its features, see its documentation.
Customizing Builds with Release Profiles
In Rust, release profiles are predefined and customizable profiles with different configurations that allow a programmer to have more control over various options for compiling code. Each profile is configured independently of the others.
Cargo has two main profiles: the dev
profile Cargo uses when you run cargo build
and the release
profile Cargo uses when you run cargo build --release
. The dev
profile is defined with good defaults for development,
and the release
profile has good defaults for release builds.
These profile names might be familiar from the output of your builds:
$ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
$ cargo build --release
Finished release [optimized] target(s) in 0.0s
The dev
and release
are these different profiles used by the compiler.
Cargo has default settings for each of the profiles that apply when you haven't
explicitly added any [profile.*]
sections in the project’s Cargo.toml file.
By adding [profile.*]
sections for any profile you want to customize, you
override any subset of the default settings. For example, here are the default
values for the opt-level
setting for the dev
and release
profiles:
Filename: Cargo.toml
[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
The opt-level
setting controls the number of optimizations Rust will apply to
your code, with a range of 0 to 3. Applying more optimizations extends
compiling time, so if you’re in development and compiling your code often,
you’ll want fewer optimizations to compile faster even if the resulting code
runs slower. The default opt-level
for dev
is therefore 0
. When you’re
ready to release your code, it’s best to spend more time compiling. You’ll only
compile in release mode once, but you’ll run the compiled program many times,
so release mode trades longer compile time for code that runs faster. That is
why the default opt-level
for the release
profile is 3
.
You can override a default setting by adding a different value for it in Cargo.toml. For example, if we want to use optimization level 1 in the development profile, we can add these two lines to our project’s Cargo.toml file:
Filename: Cargo.toml
[profile.dev]
opt-level = 1
This code overrides the default setting of 0
. Now when we run cargo build
,
Cargo will use the defaults for the dev
profile plus our customization to
opt-level
. Because we set opt-level
to 1
, Cargo will apply more
optimizations than the default, but not as many as in a release build.
For the full list of configuration options and defaults for each profile, see Cargo’s documentation.
Publishing a Crate to Crates.io
We’ve used packages from crates.io as dependencies of our project, but you can also share your code with other people by publishing your own packages. The crate registry at crates.io distributes the source code of your packages, so it primarily hosts code that is open source.
Rust and Cargo have features that make your published package easier for people to find and use. We’ll talk about some of these features next and then explain how to publish a package.
Making Useful Documentation Comments
Accurately documenting your packages will help other users know how and when to
use them, so it’s worth investing the time to write documentation. In Chapter
3, we discussed how to comment Rust code using two slashes, //
. Rust also has
a particular kind of comment for documentation, known conveniently as a
documentation comment, that will generate HTML documentation. The HTML
displays the contents of documentation comments for public API items intended
for programmers interested in knowing how to use your crate as opposed to how
your crate is implemented.
Documentation comments use three slashes, ///
, instead of two and support
Markdown notation for formatting the text. Place documentation comments just
before the item they’re documenting. Listing 14-1 shows documentation comments
for an add_one
function in a crate named my_crate
.
Filename: src/lib.rs
/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
Here, we give a description of what the add_one
function does, start a
section with the heading Examples
, and then provide code that demonstrates
how to use the add_one
function. We can generate the HTML documentation from
this documentation comment by running cargo doc
. This command runs the
rustdoc
tool distributed with Rust and puts the generated HTML documentation
in the target/doc directory.
For convenience, running cargo doc --open
will build the HTML for your
current crate’s documentation (as well as the documentation for all of your
crate’s dependencies) and open the result in a web browser. Navigate to the
add_one
function and you’ll see how the text in the documentation comments is
rendered, as shown in Figure 14-1:
Commonly Used Sections
We used the # Examples
Markdown heading in Listing 14-1 to create a section
in the HTML with the title “Examples.” Here are some other sections that crate
authors commonly use in their documentation:
- Panics: The scenarios in which the function being documented could panic. Callers of the function who don’t want their programs to panic should make sure they don’t call the function in these situations.
- Errors: If the function returns a
Result
, describing the kinds of errors that might occur and what conditions might cause those errors to be returned can be helpful to callers so they can write code to handle the different kinds of errors in different ways. - Safety: If the function is
unsafe
to call (we discuss unsafety in Chapter 19), there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold.
Most documentation comments don’t need all of these sections, but this is a good checklist to remind you of the aspects of your code users will be interested in knowing about.
Documentation Comments as Tests
Adding example code blocks in your documentation comments can help demonstrate
how to use your library, and doing so has an additional bonus: running cargo test
will run the code examples in your documentation as tests! Nothing is
better than documentation with examples. But nothing is worse than examples
that don’t work because the code has changed since the documentation was
written. If we run cargo test
with the documentation for the add_one
function from Listing 14-1, we will see a section in the test results like this:
Doc-tests my_crate
running 1 test
test src/lib.rs - add_one (line 5) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s
Now if we change either the function or the example so the assert_eq!
in the
example panics and run cargo test
again, we’ll see that the doc tests catch
that the example and the code are out of sync with each other!
Commenting Contained Items
The style of doc comment //!
adds documentation to the item that contains the
comments rather than to the items following the comments. We typically use
these doc comments inside the crate root file (src/lib.rs by convention) or
inside a module to document the crate or the module as a whole.
For example, to add documentation that describes the purpose of the my_crate
crate that contains the add_one
function, we add documentation comments that
start with //!
to the beginning of the src/lib.rs file, as shown in Listing
14-2:
Filename: src/lib.rs
//! # My Crate
//!
//! `my_crate` is a collection of utilities to make performing certain
//! calculations more convenient.
/// Adds one to the number given.
// --snip--
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
x + 1
}
Notice there isn’t any code after the last line that begins with //!
. Because
we started the comments with //!
instead of ///
, we’re documenting the item
that contains this comment rather than an item that follows this comment. In
this case, that item is the src/lib.rs file, which is the crate root. These
comments describe the entire crate.
When we run cargo doc --open
, these comments will display on the front
page of the documentation for my_crate
above the list of public items in the
crate, as shown in Figure 14-2:
Documentation comments within items are useful for describing crates and modules especially. Use them to explain the overall purpose of the container to help your users understand the crate’s organization.
Exporting a Convenient Public API with pub use
The structure of your public API is a major consideration when publishing a crate. People who use your crate are less familiar with the structure than you are and might have difficulty finding the pieces they want to use if your crate has a large module hierarchy.
In Chapter 7, we covered how to make items public using the pub
keyword, and
bring items into a scope with the use
keyword. However, the structure that
makes sense to you while you’re developing a crate might not be very convenient
for your users. You might want to organize your structs in a hierarchy
containing multiple levels, but then people who want to use a type you’ve
defined deep in the hierarchy might have trouble finding out that type exists.
They might also be annoyed at having to enter use
my_crate::some_module::another_module::UsefulType;
rather than use
my_crate::UsefulType;
.
The good news is that if the structure isn’t convenient for others to use
from another library, you don’t have to rearrange your internal organization:
instead, you can re-export items to make a public structure that’s different
from your private structure by using pub use
. Re-exporting takes a public
item in one location and makes it public in another location, as if it were
defined in the other location instead.
For example, say we made a library named art
for modeling artistic concepts.
Within this library are two modules: a kinds
module containing two enums
named PrimaryColor
and SecondaryColor
and a utils
module containing a
function named mix
, as shown in Listing 14-3:
Filename: src/lib.rs
//! # Art
//!
//! A library for modeling artistic concepts.
pub mod kinds {
/// The primary colors according to the RYB color model.
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
/// The secondary colors according to the RYB color model.
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils {
use crate::kinds::*;
/// Combines two primary colors in equal amounts to create
/// a secondary color.
pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
// --snip--
unimplemented!();
}
}
Figure 14-3 shows what the front page of the documentation for this crate
generated by cargo doc
would look like:
Note that the PrimaryColor
and SecondaryColor
types aren’t listed on the
front page, nor is the mix
function. We have to click kinds
and utils
to
see them.
Another crate that depends on this library would need use
statements that
bring the items from art
into scope, specifying the module structure that’s
currently defined. Listing 14-4 shows an example of a crate that uses the
PrimaryColor
and mix
items from the art
crate:
Filename: src/main.rs
use art::kinds::PrimaryColor;
use art::utils::mix;
fn main() {
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}
The author of the code in Listing 14-4, which uses the art
crate, had to
figure out that PrimaryColor
is in the kinds
module and mix
is in the
utils
module. The module structure of the art
crate is more relevant to
developers working on the art
crate than to those using it. The internal
structure doesn’t contain any useful information for someone trying to
understand how to use the art
crate, but rather causes confusion because
developers who use it have to figure out where to look, and must specify the
module names in the use
statements.
To remove the internal organization from the public API, we can modify the
art
crate code in Listing 14-3 to add pub use
statements to re-export the
items at the top level, as shown in Listing 14-5:
Filename: src/lib.rs
//! # Art
//!
//! A library for modeling artistic concepts.
pub use self::kinds::PrimaryColor;
pub use self::kinds::SecondaryColor;
pub use self::utils::mix;
pub mod kinds {
// --snip--
/// The primary colors according to the RYB color model.
pub enum PrimaryColor {
Red,
Yellow,
Blue,
}
/// The secondary colors according to the RYB color model.
pub enum SecondaryColor {
Orange,
Green,
Purple,
}
}
pub mod utils {
// --snip--
use crate::kinds::*;
/// Combines two primary colors in equal amounts to create
/// a secondary color.
pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor {
SecondaryColor::Orange
}
}
The API documentation that cargo doc
generates for this crate will now list
and link re-exports on the front page, as shown in Figure 14-4, making the
PrimaryColor
and SecondaryColor
types and the mix
function easier to find.
The art
crate users can still see and use the internal structure from Listing
14-3 as demonstrated in Listing 14-4, or they can use the more convenient
structure in Listing 14-5, as shown in Listing 14-6:
Filename: src/main.rs
use art::mix;
use art::PrimaryColor;
fn main() {
// --snip--
let red = PrimaryColor::Red;
let yellow = PrimaryColor::Yellow;
mix(red, yellow);
}
In cases where there are many nested modules, re-exporting the types at the top
level with pub use
can make a significant difference in the experience of
people who use the crate. Another common use of pub use
is to re-export
definitions of a dependency in the current crate to make that crate's
definitions part of your crate’s public API.
Creating a useful public API structure is more of an art than a science, and
you can iterate to find the API that works best for your users. Choosing pub use
gives you flexibility in how you structure your crate internally and
decouples that internal structure from what you present to your users. Look at
some of the code of crates you’ve installed to see if their internal structure
differs from their public API.
Setting Up a Crates.io Account
Before you can publish any crates, you need to create an account on
crates.io and get an API token. To do so,
visit the home page at crates.io and log
in via a GitHub account. (The GitHub account is currently a requirement, but
the site might support other ways of creating an account in the future.) Once
you’re logged in, visit your account settings at
https://crates.io/me/ and retrieve your
API key. Then run the cargo login
command with your API key, like this:
$ cargo login abcdefghijklmnopqrstuvwxyz012345
This command will inform Cargo of your API token and store it locally in ~/.cargo/credentials. Note that this token is a secret: do not share it with anyone else. If you do share it with anyone for any reason, you should revoke it and generate a new token on crates.io.
Adding Metadata to a New Crate
Let’s say you have a crate you want to publish. Before publishing, you’ll need
to add some metadata in the [package]
section of the crate’s Cargo.toml
file.
Your crate will need a unique name. While you’re working on a crate locally,
you can name a crate whatever you’d like. However, crate names on
crates.io are allocated on a first-come,
first-served basis. Once a crate name is taken, no one else can publish a crate
with that name. Before attempting to publish a crate, search for the name you
want to use. If the name has been used, you will need to find another name and
edit the name
field in the Cargo.toml file under the [package]
section to
use the new name for publishing, like so:
Filename: Cargo.toml
[package]
name = "guessing_game"
Even if you’ve chosen a unique name, when you run cargo publish
to publish
the crate at this point, you’ll get a warning and then an error:
$ cargo publish
Updating crates.io index
warning: manifest has no description, license, license-file, documentation, homepage or repository.
See https://doc.rust-lang.org/cargo/reference/manifest.html#package-metadata for more info.
--snip--
error: failed to publish to registry at https://crates.io
Caused by:
the remote server responded with an error: missing or empty metadata fields: description, license. Please see https://doc.rust-lang.org/cargo/reference/manifest.html for how to upload metadata
This errors because you’re missing some crucial information: a description and
license are required so people will know what your crate does and under what
terms they can use it. In Cargo.toml, add a description that's just a
sentence or two, because it will appear with your crate in search results. For
the license
field, you need to give a license identifier value. The Linux
Foundation’s Software Package Data Exchange (SPDX) lists the identifiers
you can use for this value. For example, to specify that you’ve licensed your
crate using the MIT License, add the MIT
identifier:
Filename: Cargo.toml
[package]
name = "guessing_game"
license = "MIT"
If you want to use a license that doesn’t appear in the SPDX, you need to place
the text of that license in a file, include the file in your project, and then
use license-file
to specify the name of that file instead of using the
license
key.
Guidance on which license is appropriate for your project is beyond the scope
of this book. Many people in the Rust community license their projects in the
same way as Rust by using a dual license of MIT OR Apache-2.0
. This practice
demonstrates that you can also specify multiple license identifiers separated
by OR
to have multiple licenses for your project.
With a unique name, the version, your description, and a license added, the Cargo.toml file for a project that is ready to publish might look like this:
Filename: Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"
[dependencies]
Cargo’s documentation describes other metadata you can specify to ensure others can discover and use your crate more easily.
Publishing to Crates.io
Now that you’ve created an account, saved your API token, chosen a name for your crate, and specified the required metadata, you’re ready to publish! Publishing a crate uploads a specific version to crates.io for others to use.
Be careful, because a publish is permanent. The version can never be overwritten, and the code cannot be deleted. One major goal of crates.io is to act as a permanent archive of code so that builds of all projects that depend on crates from crates.io will continue to work. Allowing version deletions would make fulfilling that goal impossible. However, there is no limit to the number of crate versions you can publish.
Run the cargo publish
command again. It should succeed now:
$ cargo publish
Updating crates.io index
Packaging guessing_game v0.1.0 (file:///projects/guessing_game)
Verifying guessing_game v0.1.0 (file:///projects/guessing_game)
Compiling guessing_game v0.1.0
(file:///projects/guessing_game/target/package/guessing_game-0.1.0)
Finished dev [unoptimized + debuginfo] target(s) in 0.19s
Uploading guessing_game v0.1.0 (file:///projects/guessing_game)
Congratulations! You’ve now shared your code with the Rust community, and anyone can easily add your crate as a dependency of their project.
Publishing a New Version of an Existing Crate
When you’ve made changes to your crate and are ready to release a new version,
you change the version
value specified in your Cargo.toml file and
republish. Use the Semantic Versioning rules to decide what an
appropriate next version number is based on the kinds of changes you’ve made.
Then run cargo publish
to upload the new version.
Deprecating Versions from Crates.io with cargo yank
Although you can’t remove previous versions of a crate, you can prevent any future projects from adding them as a new dependency. This is useful when a crate version is broken for one reason or another. In such situations, Cargo supports yanking a crate version.
Yanking a version prevents new projects from depending on that version while allowing all existing projects that depend on it to continue. Essentially, a yank means that all projects with a Cargo.lock will not break, and any future Cargo.lock files generated will not use the yanked version.
To yank a version of a crate, in the directory of the crate that you’ve
previously published, run cargo yank
and specify which version you want to
yank. For example, if we've published a crate named guessing_game
version
1.0.1 and we want to yank it, in the project directory for guessing_game
we'd
run:
$ cargo yank --vers 1.0.1
Updating crates.io index
Yank guessing_game@1.0.1
By adding --undo
to the command, you can also undo a yank and allow projects
to start depending on a version again:
$ cargo yank --vers 1.0.1 --undo
Updating crates.io index
Unyank guessing_game@1.0.1
A yank does not delete any code. It cannot, for example, delete accidentally uploaded secrets. If that happens, you must reset those secrets immediately.
Cargo Workspaces
In Chapter 12, we built a package that included a binary crate and a library crate. As your project develops, you might find that the library crate continues to get bigger and you want to split your package further into multiple library crates. Cargo offers a feature called workspaces that can help manage multiple related packages that are developed in tandem.
Creating a Workspace
A workspace is a set of packages that share the same Cargo.lock and output
directory. Let’s make a project using a workspace—we’ll use trivial code so we
can concentrate on the structure of the workspace. There are multiple ways to
structure a workspace, so we'll just show one common way. We’ll have a
workspace containing a binary and two libraries. The binary, which will provide
the main functionality, will depend on the two libraries. One library will
provide an add_one
function, and a second library an add_two
function.
These three crates will be part of the same workspace. We’ll start by creating
a new directory for the workspace:
$ mkdir add
$ cd add
Next, in the add directory, we create the Cargo.toml file that will
configure the entire workspace. This file won’t have a [package]
section.
Instead, it will start with a [workspace]
section that will allow us to add
members to the workspace by specifying the path to the package with our binary
crate; in this case, that path is adder:
Filename: Cargo.toml
[workspace]
members = [
"adder",
]
Next, we’ll create the adder
binary crate by running cargo new
within the
add directory:
$ cargo new adder
Created binary (application) `adder` package
At this point, we can build the workspace by running cargo build
. The files
in your add directory should look like this:
├── Cargo.lock
├── Cargo.toml
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
The workspace has one target directory at the top level that the compiled
artifacts will be placed into; the adder
package doesn’t have its own
target directory. Even if we were to run cargo build
from inside the
adder directory, the compiled artifacts would still end up in add/target
rather than add/adder/target. Cargo structures the target directory in a
workspace like this because the crates in a workspace are meant to depend on
each other. If each crate had its own target directory, each crate would have
to recompile each of the other crates in the workspace to place the artifacts
in its own target directory. By sharing one target directory, the crates
can avoid unnecessary rebuilding.
Creating the Second Package in the Workspace
Next, let’s create another member package in the workspace and call it
add_one
. Change the top-level Cargo.toml to specify the add_one path in
the members
list:
Filename: Cargo.toml
[workspace]
members = [
"adder",
"add_one",
]
Then generate a new library crate named add_one
:
$ cargo new add_one --lib
Created library `add_one` package
Your add directory should now have these directories and files:
├── Cargo.lock
├── Cargo.toml
├── add_one
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
In the add_one/src/lib.rs file, let’s add an add_one
function:
Filename: add_one/src/lib.rs
pub fn add_one(x: i32) -> i32 {
x + 1
}
Now we can have the adder
package with our binary depend on the add_one
package that has our library. First, we’ll need to add a path dependency on
add_one
to adder/Cargo.toml.
Filename: adder/Cargo.toml
[dependencies]
add_one = { path = "../add_one" }
Cargo doesn’t assume that crates in a workspace will depend on each other, so we need to be explicit about the dependency relationships.
Next, let’s use the add_one
function (from the add_one
crate) in the
adder
crate. Open the adder/src/main.rs file and add a use
line at the
top to bring the new add_one
library crate into scope. Then change the main
function to call the add_one
function, as in Listing 14-7.
Filename: adder/src/main.rs
use add_one;
fn main() {
let num = 10;
println!("Hello, world! {num} plus one is {}!", add_one::add_one(num));
}
Let’s build the workspace by running cargo build
in the top-level add
directory!
$ cargo build
Compiling add_one v0.1.0 (file:///projects/add/add_one)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished dev [unoptimized + debuginfo] target(s) in 0.68s
To run the binary crate from the add directory, we can specify which
package in the workspace we want to run by using the -p
argument and the
package name with cargo run
:
$ cargo run -p adder
Finished dev [unoptimized + debuginfo] target(s) in 0.0s
Running `target/debug/adder`
Hello, world! 10 plus one is 11!
This runs the code in adder/src/main.rs, which depends on the add_one
crate.
Depending on an External Package in a Workspace
Notice that the workspace has only one Cargo.lock file at the top level,
rather than having a Cargo.lock in each crate’s directory. This ensures that
all crates are using the same version of all dependencies. If we add the rand
package to the adder/Cargo.toml and add_one/Cargo.toml files, Cargo will
resolve both of those to one version of rand
and record that in the one
Cargo.lock. Making all crates in the workspace use the same dependencies
means the crates will always be compatible with each other. Let’s add the
rand
crate to the [dependencies]
section in the add_one/Cargo.toml file
so we can use the rand
crate in the add_one
crate:
Filename: add_one/Cargo.toml
[dependencies]
rand = "0.8.5"
We can now add use rand;
to the add_one/src/lib.rs file, and building the
whole workspace by running cargo build
in the add directory will bring in
and compile the rand
crate. We will get one warning because we aren’t
referring to the rand
we brought into scope:
$ cargo build
Updating crates.io index
Downloaded rand v0.8.5
--snip--
Compiling rand v0.8.5
Compiling add_one v0.1.0 (file:///projects/add/add_one)
warning: unused import: `rand`
--> add_one/src/lib.rs:1:5
|
1 | use rand;
| ^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: `add_one` (lib) generated 1 warning
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished dev [unoptimized + debuginfo] target(s) in 10.18s
The top-level Cargo.lock now contains information about the dependency of
add_one
on rand
. However, even though rand
is used somewhere in the
workspace, we can’t use it in other crates in the workspace unless we add
rand
to their Cargo.toml files as well. For example, if we add use rand;
to the adder/src/main.rs file for the adder
package, we’ll get an error:
$ cargo build
--snip--
Compiling adder v0.1.0 (file:///projects/add/adder)
error[E0432]: unresolved import `rand`
--> adder/src/main.rs:2:5
|
2 | use rand;
| ^^^^ no external crate `rand`
To fix this, edit the Cargo.toml file for the adder
package and indicate
that rand
is a dependency for it as well. Building the adder
package will
add rand
to the list of dependencies for adder
in Cargo.lock, but no
additional copies of rand
will be downloaded. Cargo has ensured that every
crate in every package in the workspace using the rand
package will be using
the same version, saving us space and ensuring that the crates in the workspace
will be compatible with each other.
Adding a Test to a Workspace
For another enhancement, let’s add a test of the add_one::add_one
function
within the add_one
crate:
Filename: add_one/src/lib.rs
pub fn add_one(x: i32) -> i32 {
x + 1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
assert_eq!(3, add_one(2));
}
}
Now run cargo test
in the top-level add directory. Running cargo test
in
a workspace structured like this one will run the tests for all the crates in
the workspace:
$ cargo test
Compiling add_one v0.1.0 (file:///projects/add/add_one)
Compiling adder v0.1.0 (file:///projects/add/adder)
Finished test [unoptimized + debuginfo] target(s) in 0.27s
Running unittests src/lib.rs (target/debug/deps/add_one-f0253159197f7841)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/debug/deps/adder-49979ff40686fa8e)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests add_one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
The first section of the output shows that the it_works
test in the add_one
crate passed. The next section shows that zero tests were found in the adder
crate, and then the last section shows zero documentation tests were found in
the add_one
crate.
We can also run tests for one particular crate in a workspace from the
top-level directory by using the -p
flag and specifying the name of the crate
we want to test:
$ cargo test -p add_one
Finished test [unoptimized + debuginfo] target(s) in 0.00s
Running unittests src/lib.rs (target/debug/deps/add_one-b3235fea9a156f74)
running 1 test
test tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests add_one
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
This output shows cargo test
only ran the tests for the add_one
crate and
didn’t run the adder
crate tests.
If you publish the crates in the workspace to crates.io,
each crate in the workspace will need to be published separately. Like cargo test
, we can publish a particular crate in our workspace by using the -p
flag and specifying the name of the crate we want to publish.
For additional practice, add an add_two
crate to this workspace in a similar
way as the add_one
crate!
As your project grows, consider using a workspace: it’s easier to understand smaller, individual components than one big blob of code. Furthermore, keeping the crates in a workspace can make coordination between crates easier if they are often changed at the same time.
Installing Binaries with cargo install
The cargo install
command allows you to install and use binary crates
locally. This isn’t intended to replace system packages; it’s meant to be a
convenient way for Rust developers to install tools that others have shared on
crates.io. Note that you can only install
packages that have binary targets. A binary target is the runnable program
that is created if the crate has a src/main.rs file or another file specified
as a binary, as opposed to a library target that isn’t runnable on its own but
is suitable for including within other programs. Usually, crates have
information in the README file about whether a crate is a library, has a
binary target, or both.
All binaries installed with cargo install
are stored in the installation
root’s bin folder. If you installed Rust using rustup.rs and don’t have any
custom configurations, this directory will be $HOME/.cargo/bin. Ensure that
directory is in your $PATH
to be able to run programs you’ve installed with
cargo install
.
For example, in Chapter 12 we mentioned that there’s a Rust implementation of
the grep
tool called ripgrep
for searching files. To install ripgrep
, we
can run the following:
$ cargo install ripgrep
Updating crates.io index
Downloaded ripgrep v13.0.0
Downloaded 1 crate (243.3 KB) in 0.88s
Installing ripgrep v13.0.0
--snip--
Compiling ripgrep v13.0.0
Finished release [optimized + debuginfo] target(s) in 3m 10s
Installing ~/.cargo/bin/rg
Installed package `ripgrep v13.0.0` (executable `rg`)
The second-to-last line of the output shows the location and the name of the
installed binary, which in the case of ripgrep
is rg
. As long as the
installation directory is in your $PATH
, as mentioned previously, you can
then run rg --help
and start using a faster, rustier tool for searching files!
Extending Cargo with Custom Commands
Cargo is designed so you can extend it with new subcommands without having to
modify Cargo. If a binary in your $PATH
is named cargo-something
, you can
run it as if it was a Cargo subcommand by running cargo something
. Custom
commands like this are also listed when you run cargo --list
. Being able to
use cargo install
to install extensions and then run them just like the
built-in Cargo tools is a super convenient benefit of Cargo’s design!
Summary
Sharing code with Cargo and crates.io is part of what makes the Rust ecosystem useful for many different tasks. Rust’s standard library is small and stable, but crates are easy to share, use, and improve on a timeline different from that of the language. Don’t be shy about sharing code that’s useful to you on crates.io; it’s likely that it will be useful to someone else as well!
Smart Pointers
A pointer is a general concept for a variable that contains an address in
memory. This address refers to, or “points at,” some other data. The most
common kind of pointer in Rust is a reference, which you learned about in
Chapter 4. References are indicated by the &
symbol and borrow the value they
point to. They don’t have any special capabilities other than referring to
data, and have no overhead.
Smart pointers, on the other hand, are data structures that act like a pointer but also have additional metadata and capabilities. The concept of smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist in other languages as well. Rust has a variety of smart pointers defined in the standard library that provide functionality beyond that provided by references. To explore the general concept, we’ll look at a couple of different examples of smart pointers, including a reference counting smart pointer type. This pointer enables you to allow data to have multiple owners by keeping track of the number of owners and, when no owners remain, cleaning up the data.
Rust, with its concept of ownership and borrowing, has an additional difference between references and smart pointers: while references only borrow data, in many cases, smart pointers own the data they point to.
Though we didn’t call them as such at the time, we’ve already encountered a few
smart pointers in this book, including String
and Vec<T>
in Chapter 8. Both
these types count as smart pointers because they own some memory and allow you
to manipulate it. They also have metadata and extra capabilities or guarantees.
String
, for example, stores its capacity as metadata and has the extra
ability to ensure its data will always be valid UTF-8.
Smart pointers are usually implemented using structs. Unlike an ordinary
struct, smart pointers implement the Deref
and Drop
traits. The Deref
trait allows an instance of the smart pointer struct to behave like a reference
so you can write your code to work with either references or smart pointers.
The Drop
trait allows you to customize the code that’s run when an instance
of the smart pointer goes out of scope. In this chapter, we’ll discuss both
traits and demonstrate why they’re important to smart pointers.
Given that the smart pointer pattern is a general design pattern used frequently in Rust, this chapter won’t cover every existing smart pointer. Many libraries have their own smart pointers, and you can even write your own. We’ll cover the most common smart pointers in the standard library:
Box<T>
for allocating values on the heapRc<T>
, a reference counting type that enables multiple ownershipRef<T>
andRefMut<T>
, accessed throughRefCell<T>
, a type that enforces the borrowing rules at runtime instead of compile time
In addition, we’ll cover the interior mutability pattern where an immutable type exposes an API for mutating an interior value. We’ll also discuss reference cycles: how they can leak memory and how to prevent them.
Let’s dive in!
Using Box<T>
to Point to Data on the Heap
The most straightforward smart pointer is a box, whose type is written
Box<T>
. Boxes allow you to store data on the heap rather than the stack. What
remains on the stack is the pointer to the heap data. Refer to Chapter 4 to
review the difference between the stack and the heap.
Boxes don’t have performance overhead, other than storing their data on the heap instead of on the stack. But they don’t have many extra capabilities either. You’ll use them most often in these situations:
- When you have a type whose size can’t be known at compile time and you want to use a value of that type in a context that requires an exact size
- When you have a large amount of data and you want to transfer ownership but ensure the data won’t be copied when you do so
- When you want to own a value and you care only that it’s a type that implements a particular trait rather than being of a specific type
We’ll demonstrate the first situation in the “Enabling Recursive Types with Boxes” section. In the second case, transferring ownership of a large amount of data can take a long time because the data is copied around on the stack. To improve performance in this situation, we can store the large amount of data on the heap in a box. Then, only the small amount of pointer data is copied around on the stack, while the data it references stays in one place on the heap. The third case is known as a trait object, and Chapter 17 devotes an entire section, “Using Trait Objects That Allow for Values of Different Types,” just to that topic. So what you learn here you’ll apply again in Chapter 17!
Using a Box<T>
to Store Data on the Heap
Before we discuss the heap storage use case for Box<T>
, we’ll cover the
syntax and how to interact with values stored within a Box<T>
.
Listing 15-1 shows how to use a box to store an i32
value on the heap:
Filename: src/main.rs
fn main() { let b = Box::new(5); println!("b = {}", b); }
We define the variable b
to have the value of a Box
that points to the
value 5
, which is allocated on the heap. This program will print b = 5
; in
this case, we can access the data in the box similar to how we would if this
data were on the stack. Just like any owned value, when a box goes out of
scope, as b
does at the end of main
, it will be deallocated. The
deallocation happens both for the box (stored on the stack) and the data it
points to (stored on the heap).
Putting a single value on the heap isn’t very useful, so you won’t use boxes by
themselves in this way very often. Having values like a single i32
on the
stack, where they’re stored by default, is more appropriate in the majority of
situations. Let’s look at a case where boxes allow us to define types that we
wouldn’t be allowed to if we didn’t have boxes.
Enabling Recursive Types with Boxes
A value of recursive type can have another value of the same type as part of itself. Recursive types pose an issue because at compile time Rust needs to know how much space a type takes up. However, the nesting of values of recursive types could theoretically continue infinitely, so Rust can’t know how much space the value needs. Because boxes have a known size, we can enable recursive types by inserting a box in the recursive type definition.
As an example of a recursive type, let’s explore the cons list. This is a data type commonly found in functional programming languages. The cons list type we’ll define is straightforward except for the recursion; therefore, the concepts in the example we’ll work with will be useful any time you get into more complex situations involving recursive types.
More Information About the Cons List
A cons list is a data structure that comes from the Lisp programming language
and its dialects and is made up of nested pairs, and is the Lisp version of a
linked list. Its name comes from the cons
function (short for “construct
function”) in Lisp that constructs a new pair from its two arguments. By
calling cons
on a pair consisting of a value and another pair, we can
construct cons lists made up of recursive pairs.
For example, here’s a pseudocode representation of a cons list containing the list 1, 2, 3 with each pair in parentheses:
(1, (2, (3, Nil)))
Each item in a cons list contains two elements: the value of the current item
and the next item. The last item in the list contains only a value called Nil
without a next item. A cons list is produced by recursively calling the cons
function. The canonical name to denote the base case of the recursion is Nil
.
Note that this is not the same as the “null” or “nil” concept in Chapter 6,
which is an invalid or absent value.
The cons list isn’t a commonly used data structure in Rust. Most of the time
when you have a list of items in Rust, Vec<T>
is a better choice to use.
Other, more complex recursive data types are useful in various situations,
but by starting with the cons list in this chapter, we can explore how boxes
let us define a recursive data type without much distraction.
Listing 15-2 contains an enum definition for a cons list. Note that this code
won’t compile yet because the List
type doesn’t have a known size, which
we’ll demonstrate.
Filename: src/main.rs
enum List {
Cons(i32, List),
Nil,
}
fn main() {}
Note: We’re implementing a cons list that holds only
i32
values for the purposes of this example. We could have implemented it using generics, as we discussed in Chapter 10, to define a cons list type that could store values of any type.
Using the List
type to store the list 1, 2, 3
would look like the code in
Listing 15-3:
Filename: src/main.rs
enum List {
Cons(i32, List),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let list = Cons(1, Cons(2, Cons(3, Nil)));
}
The first Cons
value holds 1
and another List
value. This List
value is
another Cons
value that holds 2
and another List
value. This List
value
is one more Cons
value that holds 3
and a List
value, which is finally
Nil
, the non-recursive variant that signals the end of the list.
If we try to compile the code in Listing 15-3, we get the error shown in Listing 15-4:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0072]: recursive type `List` has infinite size
--> src/main.rs:1:1
|
1 | enum List {
| ^^^^^^^^^
2 | Cons(i32, List),
| ---- recursive without indirection
|
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle
|
2 | Cons(i32, Box<List>),
| ++++ +
For more information about this error, try `rustc --explain E0072`.
error: could not compile `cons-list` due to previous error
The error shows this type “has infinite size.” The reason is that we’ve defined
List
with a variant that is recursive: it holds another value of itself
directly. As a result, Rust can’t figure out how much space it needs to store a
List
value. Let’s break down why we get this error. First, we’ll look at how
Rust decides how much space it needs to store a value of a non-recursive type.
Computing the Size of a Non-Recursive Type
Recall the Message
enum we defined in Listing 6-2 when we discussed enum
definitions in Chapter 6:
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() {}
To determine how much space to allocate for a Message
value, Rust goes
through each of the variants to see which variant needs the most space. Rust
sees that Message::Quit
doesn’t need any space, Message::Move
needs enough
space to store two i32
values, and so forth. Because only one variant will be
used, the most space a Message
value will need is the space it would take to
store the largest of its variants.
Contrast this with what happens when Rust tries to determine how much space a
recursive type like the List
enum in Listing 15-2 needs. The compiler starts
by looking at the Cons
variant, which holds a value of type i32
and a value
of type List
. Therefore, Cons
needs an amount of space equal to the size of
an i32
plus the size of a List
. To figure out how much memory the List
type needs, the compiler looks at the variants, starting with the Cons
variant. The Cons
variant holds a value of type i32
and a value of type
List
, and this process continues infinitely, as shown in Figure 15-1.
Using Box<T>
to Get a Recursive Type with a Known Size
Because Rust can’t figure out how much space to allocate for recursively defined types, the compiler gives an error with this helpful suggestion:
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable
|
2 | Cons(i32, Box<List>),
| ++++ +
In this suggestion, “indirection” means that instead of storing a value directly, we should change the data structure to store the value indirectly by storing a pointer to the value instead.
Because a Box<T>
is a pointer, Rust always knows how much space a Box<T>
needs: a pointer’s size doesn’t change based on the amount of data it’s
pointing to. This means we can put a Box<T>
inside the Cons
variant instead
of another List
value directly. The Box<T>
will point to the next List
value that will be on the heap rather than inside the Cons
variant.
Conceptually, we still have a list, created with lists holding other lists, but
this implementation is now more like placing the items next to one another
rather than inside one another.
We can change the definition of the List
enum in Listing 15-2 and the usage
of the List
in Listing 15-3 to the code in Listing 15-5, which will compile:
Filename: src/main.rs
enum List { Cons(i32, Box<List>), Nil, } use crate::List::{Cons, Nil}; fn main() { let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); }
The Cons
variant needs the size of an i32
plus the space to store the
box’s pointer data. The Nil
variant stores no values, so it needs less space
than the Cons
variant. We now know that any List
value will take up the
size of an i32
plus the size of a box’s pointer data. By using a box, we’ve
broken the infinite, recursive chain, so the compiler can figure out the size
it needs to store a List
value. Figure 15-2 shows what the Cons
variant
looks like now.
Boxes provide only the indirection and heap allocation; they don’t have any other special capabilities, like those we’ll see with the other smart pointer types. They also don’t have the performance overhead that these special capabilities incur, so they can be useful in cases like the cons list where the indirection is the only feature we need. We’ll look at more use cases for boxes in Chapter 17, too.
The Box<T>
type is a smart pointer because it implements the Deref
trait,
which allows Box<T>
values to be treated like references. When a Box<T>
value goes out of scope, the heap data that the box is pointing to is cleaned
up as well because of the Drop
trait implementation. These two traits will be
even more important to the functionality provided by the other smart pointer
types we’ll discuss in the rest of this chapter. Let’s explore these two traits
in more detail.
Treating Smart Pointers Like Regular References with the Deref
Trait
Implementing the Deref
trait allows you to customize the behavior of the
dereference operator *
(not to be confused with the multiplication or glob
operator). By implementing Deref
in such a way that a smart pointer can be
treated like a regular reference, you can write code that operates on
references and use that code with smart pointers too.
Let’s first look at how the dereference operator works with regular references.
Then we’ll try to define a custom type that behaves like Box<T>
, and see why
the dereference operator doesn’t work like a reference on our newly defined
type. We’ll explore how implementing the Deref
trait makes it possible for
smart pointers to work in ways similar to references. Then we’ll look at
Rust’s deref coercion feature and how it lets us work with either references
or smart pointers.
Note: there’s one big difference between the
MyBox<T>
type we’re about to build and the realBox<T>
: our version will not store its data on the heap. We are focusing this example onDeref
, so where the data is actually stored is less important than the pointer-like behavior.
Following the Pointer to the Value
A regular reference is a type of pointer, and one way to think of a pointer is
as an arrow to a value stored somewhere else. In Listing 15-6, we create a
reference to an i32
value and then use the dereference operator to follow the
reference to the value:
Filename: src/main.rs
fn main() { let x = 5; let y = &x; assert_eq!(5, x); assert_eq!(5, *y); }
The variable x
holds an i32
value 5
. We set y
equal to a reference to
x
. We can assert that x
is equal to 5
. However, if we want to make an
assertion about the value in y
, we have to use *y
to follow the reference
to the value it’s pointing to (hence dereference) so the compiler can compare
the actual value. Once we dereference y
, we have access to the integer value
y
is pointing to that we can compare with 5
.
If we tried to write assert_eq!(5, y);
instead, we would get this compilation
error:
$ cargo run
Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0277]: can't compare `{integer}` with `&{integer}`
--> src/main.rs:6:5
|
6 | assert_eq!(5, y);
| ^^^^^^^^^^^^^^^^ no implementation for `{integer} == &{integer}`
|
= help: the trait `PartialEq<&{integer}>` is not implemented for `{integer}`
= help: the following other types implement trait `PartialEq<Rhs>`:
f32
f64
i128
i16
i32
i64
i8
isize
and 6 others
= note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0277`.
error: could not compile `deref-example` due to previous error
Comparing a number and a reference to a number isn’t allowed because they’re different types. We must use the dereference operator to follow the reference to the value it’s pointing to.
Using Box<T>
Like a Reference
We can rewrite the code in Listing 15-6 to use a Box<T>
instead of a
reference; the dereference operator used on the Box<T>
in Listing 15-7
functions in the same way as the dereference operator used on the reference in
Listing 15-6:
Filename: src/main.rs
fn main() { let x = 5; let y = Box::new(x); assert_eq!(5, x); assert_eq!(5, *y); }
The main difference between Listing 15-7 and Listing 15-6 is that here we set
y
to be an instance of a Box<T>
pointing to a copied value of x
rather
than a reference pointing to the value of x
. In the last assertion, we can
use the dereference operator to follow the pointer of the Box<T>
in the same
way that we did when y
was a reference. Next, we’ll explore what is special
about Box<T>
that enables us to use the dereference operator by defining our
own type.
Defining Our Own Smart Pointer
Let’s build a smart pointer similar to the Box<T>
type provided by the
standard library to experience how smart pointers behave differently from
references by default. Then we’ll look at how to add the ability to use the
dereference operator.
The Box<T>
type is ultimately defined as a tuple struct with one element, so
Listing 15-8 defines a MyBox<T>
type in the same way. We’ll also define a
new
function to match the new
function defined on Box<T>
.
Filename: src/main.rs
struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() {}
We define a struct named MyBox
and declare a generic parameter T
, because
we want our type to hold values of any type. The MyBox
type is a tuple struct
with one element of type T
. The MyBox::new
function takes one parameter of
type T
and returns a MyBox
instance that holds the value passed in.
Let’s try adding the main
function in Listing 15-7 to Listing 15-8 and
changing it to use the MyBox<T>
type we’ve defined instead of Box<T>
. The
code in Listing 15-9 won’t compile because Rust doesn’t know how to dereference
MyBox
.
Filename: src/main.rs
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
fn main() {
let x = 5;
let y = MyBox::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
}
Here’s the resulting compilation error:
$ cargo run
Compiling deref-example v0.1.0 (file:///projects/deref-example)
error[E0614]: type `MyBox<{integer}>` cannot be dereferenced
--> src/main.rs:14:19
|
14 | assert_eq!(5, *y);
| ^^
For more information about this error, try `rustc --explain E0614`.
error: could not compile `deref-example` due to previous error
Our MyBox<T>
type can’t be dereferenced because we haven’t implemented that
ability on our type. To enable dereferencing with the *
operator, we
implement the Deref
trait.
Treating a Type Like a Reference by Implementing the Deref
Trait
As discussed in the “Implementing a Trait on a Type” section of Chapter 10, to implement a trait, we need to provide
implementations for the trait’s required methods. The Deref
trait, provided
by the standard library, requires us to implement one method named deref
that
borrows self
and returns a reference to the inner data. Listing 15-10
contains an implementation of Deref
to add to the definition of MyBox
:
Filename: src/main.rs
use std::ops::Deref; impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &Self::Target { &self.0 } } struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn main() { let x = 5; let y = MyBox::new(x); assert_eq!(5, x); assert_eq!(5, *y); }
The type Target = T;
syntax defines an associated type for the Deref
trait to use. Associated types are a slightly different way of declaring a
generic parameter, but you don’t need to worry about them for now; we’ll cover
them in more detail in Chapter 19.
We fill in the body of the deref
method with &self.0
so deref
returns a
reference to the value we want to access with the *
operator; recall from the
“Using Tuple Structs without Named Fields to Create Different
Types” section of Chapter 5 that .0
accesses
the first value in a tuple struct. The main
function in Listing 15-9 that
calls *
on the MyBox<T>
value now compiles, and the assertions pass!
Without the Deref
trait, the compiler can only dereference &
references.
The deref
method gives the compiler the ability to take a value of any type
that implements Deref
and call the deref
method to get a &
reference that
it knows how to dereference.
When we entered *y
in Listing 15-9, behind the scenes Rust actually ran this
code:
*(y.deref())
Rust substitutes the *
operator with a call to the deref
method and then a
plain dereference so we don’t have to think about whether or not we need to
call the deref
method. This Rust feature lets us write code that functions
identically whether we have a regular reference or a type that implements
Deref
.
The reason the deref
method returns a reference to a value, and that the
plain dereference outside the parentheses in *(y.deref())
is still necessary,
is to do with the ownership system. If the deref
method returned the value
directly instead of a reference to the value, the value would be moved out of
self
. We don’t want to take ownership of the inner value inside MyBox<T>
in
this case or in most cases where we use the dereference operator.
Note that the *
operator is replaced with a call to the deref
method and
then a call to the *
operator just once, each time we use a *
in our code.
Because the substitution of the *
operator does not recurse infinitely, we
end up with data of type i32
, which matches the 5
in assert_eq!
in
Listing 15-9.
Implicit Deref Coercions with Functions and Methods
Deref coercion converts a reference to a type that implements the Deref
trait into a reference to another type. For example, deref coercion can convert
&String
to &str
because String
implements the Deref
trait such that it
returns &str
. Deref coercion is a convenience Rust performs on arguments to
functions and methods, and works only on types that implement the Deref
trait. It happens automatically when we pass a reference to a particular type’s
value as an argument to a function or method that doesn’t match the parameter
type in the function or method definition. A sequence of calls to the deref
method converts the type we provided into the type the parameter needs.
Deref coercion was added to Rust so that programmers writing function and
method calls don’t need to add as many explicit references and dereferences
with &
and *
. The deref coercion feature also lets us write more code that
can work for either references or smart pointers.
To see deref coercion in action, let’s use the MyBox<T>
type we defined in
Listing 15-8 as well as the implementation of Deref
that we added in Listing
15-10. Listing 15-11 shows the definition of a function that has a string slice
parameter:
Filename: src/main.rs
fn hello(name: &str) { println!("Hello, {name}!"); } fn main() {}
We can call the hello
function with a string slice as an argument, such as
hello("Rust");
for example. Deref coercion makes it possible to call hello
with a reference to a value of type MyBox<String>
, as shown in Listing 15-12:
Filename: src/main.rs
use std::ops::Deref; impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn hello(name: &str) { println!("Hello, {name}!"); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&m); }
Here we’re calling the hello
function with the argument &m
, which is a
reference to a MyBox<String>
value. Because we implemented the Deref
trait
on MyBox<T>
in Listing 15-10, Rust can turn &MyBox<String>
into &String
by calling deref
. The standard library provides an implementation of Deref
on String
that returns a string slice, and this is in the API documentation
for Deref
. Rust calls deref
again to turn the &String
into &str
, which
matches the hello
function’s definition.
If Rust didn’t implement deref coercion, we would have to write the code in
Listing 15-13 instead of the code in Listing 15-12 to call hello
with a value
of type &MyBox<String>
.
Filename: src/main.rs
use std::ops::Deref; impl<T> Deref for MyBox<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } } fn hello(name: &str) { println!("Hello, {name}!"); } fn main() { let m = MyBox::new(String::from("Rust")); hello(&(*m)[..]); }
The (*m)
dereferences the MyBox<String>
into a String
. Then the &
and
[..]
take a string slice of the String
that is equal to the whole string to
match the signature of hello
. This code without deref coercions is harder to
read, write, and understand with all of these symbols involved. Deref coercion
allows Rust to handle these conversions for us automatically.
When the Deref
trait is defined for the types involved, Rust will analyze the
types and use Deref::deref
as many times as necessary to get a reference to
match the parameter’s type. The number of times that Deref::deref
needs to be
inserted is resolved at compile time, so there is no runtime penalty for taking
advantage of deref coercion!
How Deref Coercion Interacts with Mutability
Similar to how you use the Deref
trait to override the *
operator on
immutable references, you can use the DerefMut
trait to override the *
operator on mutable references.
Rust does deref coercion when it finds types and trait implementations in three cases:
- From
&T
to&U
whenT: Deref<Target=U>
- From
&mut T
to&mut U
whenT: DerefMut<Target=U>
- From
&mut T
to&U
whenT: Deref<Target=U>
The first two cases are the same as each other except that the second
implements mutability. The first case states that if you have a &T
, and T
implements Deref
to some type U
, you can get a &U
transparently. The
second case states that the same deref coercion happens for mutable references.
The third case is trickier: Rust will also coerce a mutable reference to an immutable one. But the reverse is not possible: immutable references will never coerce to mutable references. Because of the borrowing rules, if you have a mutable reference, that mutable reference must be the only reference to that data (otherwise, the program wouldn’t compile). Converting one mutable reference to one immutable reference will never break the borrowing rules. Converting an immutable reference to a mutable reference would require that the initial immutable reference is the only immutable reference to that data, but the borrowing rules don’t guarantee that. Therefore, Rust can’t make the assumption that converting an immutable reference to a mutable reference is possible.
Running Code on Cleanup with the Drop
Trait
The second trait important to the smart pointer pattern is Drop
, which lets
you customize what happens when a value is about to go out of scope. You can
provide an implementation for the Drop
trait on any type, and that code can
be used to release resources like files or network connections.
We’re introducing Drop
in the context of smart pointers because the
functionality of the Drop
trait is almost always used when implementing a
smart pointer. For example, when a Box<T>
is dropped it will deallocate the
space on the heap that the box points to.
In some languages, for some types, the programmer must call code to free memory or resources every time they finish using an instance of those types. Examples include file handles, sockets, or locks. If they forget, the system might become overloaded and crash. In Rust, you can specify that a particular bit of code be run whenever a value goes out of scope, and the compiler will insert this code automatically. As a result, you don’t need to be careful about placing cleanup code everywhere in a program that an instance of a particular type is finished with—you still won’t leak resources!
You specify the code to run when a value goes out of scope by implementing the
Drop
trait. The Drop
trait requires you to implement one method named
drop
that takes a mutable reference to self
. To see when Rust calls drop
,
let’s implement drop
with println!
statements for now.
Listing 15-14 shows a CustomSmartPointer
struct whose only custom
functionality is that it will print Dropping CustomSmartPointer!
when the
instance goes out of scope, to show when Rust runs the drop
function.
Filename: src/main.rs
struct CustomSmartPointer { data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } } fn main() { let c = CustomSmartPointer { data: String::from("my stuff"), }; let d = CustomSmartPointer { data: String::from("other stuff"), }; println!("CustomSmartPointers created."); }
The Drop
trait is included in the prelude, so we don’t need to bring it into
scope. We implement the Drop
trait on CustomSmartPointer
and provide an
implementation for the drop
method that calls println!
. The body of the
drop
function is where you would place any logic that you wanted to run when
an instance of your type goes out of scope. We’re printing some text here to
demonstrate visually when Rust will call drop
.
In main
, we create two instances of CustomSmartPointer
and then print
CustomSmartPointers created
. At the end of main
, our instances of
CustomSmartPointer
will go out of scope, and Rust will call the code we put
in the drop
method, printing our final message. Note that we didn’t need to
call the drop
method explicitly.
When we run this program, we’ll see the following output:
$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/drop-example`
CustomSmartPointers created.
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
Rust automatically called drop
for us when our instances went out of scope,
calling the code we specified. Variables are dropped in the reverse order of
their creation, so d
was dropped before c
. This example’s purpose is to
give you a visual guide to how the drop
method works; usually you would
specify the cleanup code that your type needs to run rather than a print
message.
Dropping a Value Early with std::mem::drop
Unfortunately, it’s not straightforward to disable the automatic drop
functionality. Disabling drop
isn’t usually necessary; the whole point of the
Drop
trait is that it’s taken care of automatically. Occasionally, however,
you might want to clean up a value early. One example is when using smart
pointers that manage locks: you might want to force the drop
method that
releases the lock so that other code in the same scope can acquire the lock.
Rust doesn’t let you call the Drop
trait’s drop
method manually; instead
you have to call the std::mem::drop
function provided by the standard library
if you want to force a value to be dropped before the end of its scope.
If we try to call the Drop
trait’s drop
method manually by modifying the
main
function from Listing 15-14, as shown in Listing 15-15, we’ll get a
compiler error:
Filename: src/main.rs
struct CustomSmartPointer {
data: String,
}
impl Drop for CustomSmartPointer {
fn drop(&mut self) {
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
}
}
fn main() {
let c = CustomSmartPointer {
data: String::from("some data"),
};
println!("CustomSmartPointer created.");
c.drop();
println!("CustomSmartPointer dropped before the end of main.");
}
When we try to compile this code, we’ll get this error:
$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
error[E0040]: explicit use of destructor method
--> src/main.rs:16:7
|
16 | c.drop();
| --^^^^--
| | |
| | explicit destructor calls not allowed
| help: consider using `drop` function: `drop(c)`
For more information about this error, try `rustc --explain E0040`.
error: could not compile `drop-example` due to previous error
This error message states that we’re not allowed to explicitly call drop
. The
error message uses the term destructor, which is the general programming term
for a function that cleans up an instance. A destructor is analogous to a
constructor, which creates an instance. The drop
function in Rust is one
particular destructor.
Rust doesn’t let us call drop
explicitly because Rust would still
automatically call drop
on the value at the end of main
. This would cause a
double free error because Rust would be trying to clean up the same value
twice.
We can’t disable the automatic insertion of drop
when a value goes out of
scope, and we can’t call the drop
method explicitly. So, if we need to force
a value to be cleaned up early, we use the std::mem::drop
function.
The std::mem::drop
function is different from the drop
method in the Drop
trait. We call it by passing as an argument the value we want to force drop.
The function is in the prelude, so we can modify main
in Listing 15-15 to
call the drop
function, as shown in Listing 15-16:
Filename: src/main.rs
struct CustomSmartPointer { data: String, } impl Drop for CustomSmartPointer { fn drop(&mut self) { println!("Dropping CustomSmartPointer with data `{}`!", self.data); } } fn main() { let c = CustomSmartPointer { data: String::from("some data"), }; println!("CustomSmartPointer created."); drop(c); println!("CustomSmartPointer dropped before the end of main."); }
Running this code will print the following:
$ cargo run
Compiling drop-example v0.1.0 (file:///projects/drop-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.73s
Running `target/debug/drop-example`
CustomSmartPointer created.
Dropping CustomSmartPointer with data `some data`!
CustomSmartPointer dropped before the end of main.
The text Dropping CustomSmartPointer with data `some data`!
is printed
between the CustomSmartPointer created.
and CustomSmartPointer dropped before the end of main.
text, showing that the drop
method code is called to
drop c
at that point.
You can use code specified in a Drop
trait implementation in many ways to
make cleanup convenient and safe: for instance, you could use it to create your
own memory allocator! With the Drop
trait and Rust’s ownership system, you
don’t have to remember to clean up because Rust does it automatically.
You also don’t have to worry about problems resulting from accidentally
cleaning up values still in use: the ownership system that makes sure
references are always valid also ensures that drop
gets called only once when
the value is no longer being used.
Now that we’ve examined Box<T>
and some of the characteristics of smart
pointers, let’s look at a few other smart pointers defined in the standard
library.
Rc<T>
, the Reference Counted Smart Pointer
In the majority of cases, ownership is clear: you know exactly which variable owns a given value. However, there are cases when a single value might have multiple owners. For example, in graph data structures, multiple edges might point to the same node, and that node is conceptually owned by all of the edges that point to it. A node shouldn’t be cleaned up unless it doesn’t have any edges pointing to it and so has no owners.
You have to enable multiple ownership explicitly by using the Rust type
Rc<T>
, which is an abbreviation for reference counting. The Rc<T>
type
keeps track of the number of references to a value to determine whether or not
the value is still in use. If there are zero references to a value, the value
can be cleaned up without any references becoming invalid.
Imagine Rc<T>
as a TV in a family room. When one person enters to watch TV,
they turn it on. Others can come into the room and watch the TV. When the last
person leaves the room, they turn off the TV because it’s no longer being used.
If someone turns off the TV while others are still watching it, there would be
uproar from the remaining TV watchers!
We use the Rc<T>
type when we want to allocate some data on the heap for
multiple parts of our program to read and we can’t determine at compile time
which part will finish using the data last. If we knew which part would finish
last, we could just make that part the data’s owner, and the normal ownership
rules enforced at compile time would take effect.
Note that Rc<T>
is only for use in single-threaded scenarios. When we discuss
concurrency in Chapter 16, we’ll cover how to do reference counting in
multithreaded programs.
Using Rc<T>
to Share Data
Let’s return to our cons list example in Listing 15-5. Recall that we defined
it using Box<T>
. This time, we’ll create two lists that both share ownership
of a third list. Conceptually, this looks similar to Figure 15-3:
We’ll create list a
that contains 5 and then 10. Then we’ll make two more
lists: b
that starts with 3 and c
that starts with 4. Both b
and c
lists will then continue on to the first a
list containing 5 and 10. In other
words, both lists will share the first list containing 5 and 10.
Trying to implement this scenario using our definition of List
with Box<T>
won’t work, as shown in Listing 15-17:
Filename: src/main.rs
enum List {
Cons(i32, Box<List>),
Nil,
}
use crate::List::{Cons, Nil};
fn main() {
let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
let b = Cons(3, Box::new(a));
let c = Cons(4, Box::new(a));
}
When we compile this code, we get this error:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
error[E0382]: use of moved value: `a`
--> src/main.rs:11:30
|
9 | let a = Cons(5, Box::new(Cons(10, Box::new(Nil))));
| - move occurs because `a` has type `List`, which does not implement the `Copy` trait
10 | let b = Cons(3, Box::new(a));
| - value moved here
11 | let c = Cons(4, Box::new(a));
| ^ value used here after move
For more information about this error, try `rustc --explain E0382`.
error: could not compile `cons-list` due to previous error
The Cons
variants own the data they hold, so when we create the b
list, a
is moved into b
and b
owns a
. Then, when we try to use a
again when
creating c
, we’re not allowed to because a
has been moved.
We could change the definition of Cons
to hold references instead, but then
we would have to specify lifetime parameters. By specifying lifetime
parameters, we would be specifying that every element in the list will live at
least as long as the entire list. This is the case for the elements and lists
in Listing 15-17, but not in every scenario.
Instead, we’ll change our definition of List
to use Rc<T>
in place of
Box<T>
, as shown in Listing 15-18. Each Cons
variant will now hold a value
and an Rc<T>
pointing to a List
. When we create b
, instead of taking
ownership of a
, we’ll clone the Rc<List>
that a
is holding, thereby
increasing the number of references from one to two and letting a
and b
share ownership of the data in that Rc<List>
. We’ll also clone a
when
creating c
, increasing the number of references from two to three. Every time
we call Rc::clone
, the reference count to the data within the Rc<List>
will
increase, and the data won’t be cleaned up unless there are zero references to
it.
Filename: src/main.rs
enum List { Cons(i32, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::rc::Rc; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let b = Cons(3, Rc::clone(&a)); let c = Cons(4, Rc::clone(&a)); }
We need to add a use
statement to bring Rc<T>
into scope because it’s not
in the prelude. In main
, we create the list holding 5 and 10 and store it in
a new Rc<List>
in a
. Then when we create b
and c
, we call the
Rc::clone
function and pass a reference to the Rc<List>
in a
as an
argument.
We could have called a.clone()
rather than Rc::clone(&a)
, but Rust’s
convention is to use Rc::clone
in this case. The implementation of
Rc::clone
doesn’t make a deep copy of all the data like most types’
implementations of clone
do. The call to Rc::clone
only increments the
reference count, which doesn’t take much time. Deep copies of data can take a
lot of time. By using Rc::clone
for reference counting, we can visually
distinguish between the deep-copy kinds of clones and the kinds of clones that
increase the reference count. When looking for performance problems in the
code, we only need to consider the deep-copy clones and can disregard calls to
Rc::clone
.
Cloning an Rc<T>
Increases the Reference Count
Let’s change our working example in Listing 15-18 so we can see the reference
counts changing as we create and drop references to the Rc<List>
in a
.
In Listing 15-19, we’ll change main
so it has an inner scope around list c
;
then we can see how the reference count changes when c
goes out of scope.
Filename: src/main.rs
enum List { Cons(i32, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::rc::Rc; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); println!("count after creating a = {}", Rc::strong_count(&a)); let b = Cons(3, Rc::clone(&a)); println!("count after creating b = {}", Rc::strong_count(&a)); { let c = Cons(4, Rc::clone(&a)); println!("count after creating c = {}", Rc::strong_count(&a)); } println!("count after c goes out of scope = {}", Rc::strong_count(&a)); }
At each point in the program where the reference count changes, we print the
reference count, which we get by calling the Rc::strong_count
function. This
function is named strong_count
rather than count
because the Rc<T>
type
also has a weak_count
; we’ll see what weak_count
is used for in the
“Preventing Reference Cycles: Turning an Rc<T>
into a
Weak<T>
” section.
This code prints the following:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished dev [unoptimized + debuginfo] target(s) in 0.45s
Running `target/debug/cons-list`
count after creating a = 1
count after creating b = 2
count after creating c = 3
count after c goes out of scope = 2
We can see that the Rc<List>
in a
has an initial reference count of 1; then
each time we call clone
, the count goes up by 1. When c
goes out of scope,
the count goes down by 1. We don’t have to call a function to decrease the
reference count like we have to call Rc::clone
to increase the reference
count: the implementation of the Drop
trait decreases the reference count
automatically when an Rc<T>
value goes out of scope.
What we can’t see in this example is that when b
and then a
go out of scope
at the end of main
, the count is then 0, and the Rc<List>
is cleaned up
completely. Using Rc<T>
allows a single value to have multiple owners, and
the count ensures that the value remains valid as long as any of the owners
still exist.
Via immutable references, Rc<T>
allows you to share data between multiple
parts of your program for reading only. If Rc<T>
allowed you to have multiple
mutable references too, you might violate one of the borrowing rules discussed
in Chapter 4: multiple mutable borrows to the same place can cause data races
and inconsistencies. But being able to mutate data is very useful! In the next
section, we’ll discuss the interior mutability pattern and the RefCell<T>
type that you can use in conjunction with an Rc<T>
to work with this
immutability restriction.
RefCell<T>
and the Interior Mutability Pattern
Interior mutability is a design pattern in Rust that allows you to mutate
data even when there are immutable references to that data; normally, this
action is disallowed by the borrowing rules. To mutate data, the pattern uses
unsafe
code inside a data structure to bend Rust’s usual rules that govern
mutation and borrowing. Unsafe code indicates to the compiler that we’re
checking the rules manually instead of relying on the compiler to check them
for us; we will discuss unsafe code more in Chapter 19.
We can use types that use the interior mutability pattern only when we can
ensure that the borrowing rules will be followed at runtime, even though the
compiler can’t guarantee that. The unsafe
code involved is then wrapped in a
safe API, and the outer type is still immutable.
Let’s explore this concept by looking at the RefCell<T>
type that follows the
interior mutability pattern.
Enforcing Borrowing Rules at Runtime with RefCell<T>
Unlike Rc<T>
, the RefCell<T>
type represents single ownership over the data
it holds. So, what makes RefCell<T>
different from a type like Box<T>
?
Recall the borrowing rules you learned in Chapter 4:
- At any given time, you can have either (but not both) one mutable reference or any number of immutable references.
- References must always be valid.
With references and Box<T>
, the borrowing rules’ invariants are enforced at
compile time. With RefCell<T>
, these invariants are enforced at runtime.
With references, if you break these rules, you’ll get a compiler error. With
RefCell<T>
, if you break these rules, your program will panic and exit.
The advantages of checking the borrowing rules at compile time are that errors will be caught sooner in the development process, and there is no impact on runtime performance because all the analysis is completed beforehand. For those reasons, checking the borrowing rules at compile time is the best choice in the majority of cases, which is why this is Rust’s default.
The advantage of checking the borrowing rules at runtime instead is that certain memory-safe scenarios are then allowed, where they would’ve been disallowed by the compile-time checks. Static analysis, like the Rust compiler, is inherently conservative. Some properties of code are impossible to detect by analyzing the code: the most famous example is the Halting Problem, which is beyond the scope of this book but is an interesting topic to research.
Because some analysis is impossible, if the Rust compiler can’t be sure the
code complies with the ownership rules, it might reject a correct program; in
this way, it’s conservative. If Rust accepted an incorrect program, users
wouldn’t be able to trust in the guarantees Rust makes. However, if Rust
rejects a correct program, the programmer will be inconvenienced, but nothing
catastrophic can occur. The RefCell<T>
type is useful when you’re sure your
code follows the borrowing rules but the compiler is unable to understand and
guarantee that.
Similar to Rc<T>
, RefCell<T>
is only for use in single-threaded scenarios
and will give you a compile-time error if you try using it in a multithreaded
context. We’ll talk about how to get the functionality of RefCell<T>
in a
multithreaded program in Chapter 16.
Here is a recap of the reasons to choose Box<T>
, Rc<T>
, or RefCell<T>
:
Rc<T>
enables multiple owners of the same data;Box<T>
andRefCell<T>
have single owners.Box<T>
allows immutable or mutable borrows checked at compile time;Rc<T>
allows only immutable borrows checked at compile time;RefCell<T>
allows immutable or mutable borrows checked at runtime.- Because
RefCell<T>
allows mutable borrows checked at runtime, you can mutate the value inside theRefCell<T>
even when theRefCell<T>
is immutable.
Mutating the value inside an immutable value is the interior mutability pattern. Let’s look at a situation in which interior mutability is useful and examine how it’s possible.
Interior Mutability: A Mutable Borrow to an Immutable Value
A consequence of the borrowing rules is that when you have an immutable value, you can’t borrow it mutably. For example, this code won’t compile:
fn main() {
let x = 5;
let y = &mut x;
}
If you tried to compile this code, you’d get the following error:
$ cargo run
Compiling borrowing v0.1.0 (file:///projects/borrowing)
error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable
--> src/main.rs:3:13
|
2 | let x = 5;
| - help: consider changing this to be mutable: `mut x`
3 | let y = &mut x;
| ^^^^^^ cannot borrow as mutable
For more information about this error, try `rustc --explain E0596`.
error: could not compile `borrowing` due to previous error
However, there are situations in which it would be useful for a value to mutate
itself in its methods but appear immutable to other code. Code outside the
value’s methods would not be able to mutate the value. Using RefCell<T>
is
one way to get the ability to have interior mutability, but RefCell<T>
doesn’t get around the borrowing rules completely: the borrow checker in the
compiler allows this interior mutability, and the borrowing rules are checked
at runtime instead. If you violate the rules, you’ll get a panic!
instead of
a compiler error.
Let’s work through a practical example where we can use RefCell<T>
to mutate
an immutable value and see why that is useful.
A Use Case for Interior Mutability: Mock Objects
Sometimes during testing a programmer will use a type in place of another type, in order to observe particular behavior and assert it’s implemented correctly. This placeholder type is called a test double. Think of it in the sense of a “stunt double” in filmmaking, where a person steps in and substitutes for an actor to do a particular tricky scene. Test doubles stand in for other types when we’re running tests. Mock objects are specific types of test doubles that record what happens during a test so you can assert that the correct actions took place.
Rust doesn’t have objects in the same sense as other languages have objects, and Rust doesn’t have mock object functionality built into the standard library as some other languages do. However, you can definitely create a struct that will serve the same purposes as a mock object.
Here’s the scenario we’ll test: we’ll create a library that tracks a value against a maximum value and sends messages based on how close to the maximum value the current value is. This library could be used to keep track of a user’s quota for the number of API calls they’re allowed to make, for example.
Our library will only provide the functionality of tracking how close to the
maximum a value is and what the messages should be at what times. Applications
that use our library will be expected to provide the mechanism for sending the
messages: the application could put a message in the application, send an
email, send a text message, or something else. The library doesn’t need to know
that detail. All it needs is something that implements a trait we’ll provide
called Messenger
. Listing 15-20 shows the library code:
Filename: src/lib.rs
pub trait Messenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where
T: Messenger,
{
pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage_of_max >= 0.9 {
self.messenger
.send("Urgent warning: You've used up over 90% of your quota!");
} else if percentage_of_max >= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}
One important part of this code is that the Messenger
trait has one method
called send
that takes an immutable reference to self
and the text of the
message. This trait is the interface our mock object needs to implement so that
the mock can be used in the same way a real object is. The other important part
is that we want to test the behavior of the set_value
method on the
LimitTracker
. We can change what we pass in for the value
parameter, but
set_value
doesn’t return anything for us to make assertions on. We want to be
able to say that if we create a LimitTracker
with something that implements
the Messenger
trait and a particular value for max
, when we pass different
numbers for value
, the messenger is told to send the appropriate messages.
We need a mock object that, instead of sending an email or text message when we
call send
, will only keep track of the messages it’s told to send. We can
create a new instance of the mock object, create a LimitTracker
that uses the
mock object, call the set_value
method on LimitTracker
, and then check that
the mock object has the messages we expect. Listing 15-21 shows an attempt to
implement a mock object to do just that, but the borrow checker won’t allow it:
Filename: src/lib.rs
pub trait Messenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where
T: Messenger,
{
pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage_of_max >= 0.9 {
self.messenger
.send("Urgent warning: You've used up over 90% of your quota!");
} else if percentage_of_max >= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
struct MockMessenger {
sent_messages: Vec<String>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
sent_messages: vec![],
}
}
}
impl Messenger for MockMessenger {
fn send(&self, message: &str) {
self.sent_messages.push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
let mock_messenger = MockMessenger::new();
let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);
limit_tracker.set_value(80);
assert_eq!(mock_messenger.sent_messages.len(), 1);
}
}
This test code defines a MockMessenger
struct that has a sent_messages
field with a Vec
of String
values to keep track of the messages it’s told
to send. We also define an associated function new
to make it convenient to
create new MockMessenger
values that start with an empty list of messages. We
then implement the Messenger
trait for MockMessenger
so we can give a
MockMessenger
to a LimitTracker
. In the definition of the send
method, we
take the message passed in as a parameter and store it in the MockMessenger
list of sent_messages
.
In the test, we’re testing what happens when the LimitTracker
is told to set
value
to something that is more than 75 percent of the max
value. First, we
create a new MockMessenger
, which will start with an empty list of messages.
Then we create a new LimitTracker
and give it a reference to the new
MockMessenger
and a max
value of 100. We call the set_value
method on the
LimitTracker
with a value of 80, which is more than 75 percent of 100. Then
we assert that the list of messages that the MockMessenger
is keeping track
of should now have one message in it.
However, there’s one problem with this test, as shown here:
$ cargo test
Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)
error[E0596]: cannot borrow `self.sent_messages` as mutable, as it is behind a `&` reference
--> src/lib.rs:58:13
|
2 | fn send(&self, msg: &str);
| ----- help: consider changing that to be a mutable reference: `&mut self`
...
58 | self.sent_messages.push(String::from(message));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable
For more information about this error, try `rustc --explain E0596`.
error: could not compile `limit-tracker` due to previous error
warning: build failed, waiting for other jobs to finish...
We can’t modify the MockMessenger
to keep track of the messages, because the
send
method takes an immutable reference to self
. We also can’t take the
suggestion from the error text to use &mut self
instead, because then the
signature of send
wouldn’t match the signature in the Messenger
trait
definition (feel free to try and see what error message you get).
This is a situation in which interior mutability can help! We’ll store the
sent_messages
within a RefCell<T>
, and then the send
method will be
able to modify sent_messages
to store the messages we’ve seen. Listing 15-22
shows what that looks like:
Filename: src/lib.rs
pub trait Messenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where
T: Messenger,
{
pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage_of_max >= 0.9 {
self.messenger
.send("Urgent warning: You've used up over 90% of your quota!");
} else if percentage_of_max >= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
struct MockMessenger {
sent_messages: RefCell<Vec<String>>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
sent_messages: RefCell::new(vec![]),
}
}
}
impl Messenger for MockMessenger {
fn send(&self, message: &str) {
self.sent_messages.borrow_mut().push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
// --snip--
let mock_messenger = MockMessenger::new();
let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);
limit_tracker.set_value(80);
assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
}
}
The sent_messages
field is now of type RefCell<Vec<String>>
instead of
Vec<String>
. In the new
function, we create a new RefCell<Vec<String>>
instance around the empty vector.
For the implementation of the send
method, the first parameter is still an
immutable borrow of self
, which matches the trait definition. We call
borrow_mut
on the RefCell<Vec<String>>
in self.sent_messages
to get a
mutable reference to the value inside the RefCell<Vec<String>>
, which is the
vector. Then we can call push
on the mutable reference to the vector to keep
track of the messages sent during the test.
The last change we have to make is in the assertion: to see how many items are
in the inner vector, we call borrow
on the RefCell<Vec<String>>
to get an
immutable reference to the vector.
Now that you’ve seen how to use RefCell<T>
, let’s dig into how it works!
Keeping Track of Borrows at Runtime with RefCell<T>
When creating immutable and mutable references, we use the &
and &mut
syntax, respectively. With RefCell<T>
, we use the borrow
and borrow_mut
methods, which are part of the safe API that belongs to RefCell<T>
. The
borrow
method returns the smart pointer type Ref<T>
, and borrow_mut
returns the smart pointer type RefMut<T>
. Both types implement Deref
, so we
can treat them like regular references.
The RefCell<T>
keeps track of how many Ref<T>
and RefMut<T>
smart
pointers are currently active. Every time we call borrow
, the RefCell<T>
increases its count of how many immutable borrows are active. When a Ref<T>
value goes out of scope, the count of immutable borrows goes down by one. Just
like the compile-time borrowing rules, RefCell<T>
lets us have many immutable
borrows or one mutable borrow at any point in time.
If we try to violate these rules, rather than getting a compiler error as we
would with references, the implementation of RefCell<T>
will panic at
runtime. Listing 15-23 shows a modification of the implementation of send
in
Listing 15-22. We’re deliberately trying to create two mutable borrows active
for the same scope to illustrate that RefCell<T>
prevents us from doing this
at runtime.
Filename: src/lib.rs
pub trait Messenger {
fn send(&self, msg: &str);
}
pub struct LimitTracker<'a, T: Messenger> {
messenger: &'a T,
value: usize,
max: usize,
}
impl<'a, T> LimitTracker<'a, T>
where
T: Messenger,
{
pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> {
LimitTracker {
messenger,
value: 0,
max,
}
}
pub fn set_value(&mut self, value: usize) {
self.value = value;
let percentage_of_max = self.value as f64 / self.max as f64;
if percentage_of_max >= 1.0 {
self.messenger.send("Error: You are over your quota!");
} else if percentage_of_max >= 0.9 {
self.messenger
.send("Urgent warning: You've used up over 90% of your quota!");
} else if percentage_of_max >= 0.75 {
self.messenger
.send("Warning: You've used up over 75% of your quota!");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
struct MockMessenger {
sent_messages: RefCell<Vec<String>>,
}
impl MockMessenger {
fn new() -> MockMessenger {
MockMessenger {
sent_messages: RefCell::new(vec![]),
}
}
}
impl Messenger for MockMessenger {
fn send(&self, message: &str) {
let mut one_borrow = self.sent_messages.borrow_mut();
let mut two_borrow = self.sent_messages.borrow_mut();
one_borrow.push(String::from(message));
two_borrow.push(String::from(message));
}
}
#[test]
fn it_sends_an_over_75_percent_warning_message() {
let mock_messenger = MockMessenger::new();
let mut limit_tracker = LimitTracker::new(&mock_messenger, 100);
limit_tracker.set_value(80);
assert_eq!(mock_messenger.sent_messages.borrow().len(), 1);
}
}
We create a variable one_borrow
for the RefMut<T>
smart pointer returned
from borrow_mut
. Then we create another mutable borrow in the same way in the
variable two_borrow
. This makes two mutable references in the same scope,
which isn’t allowed. When we run the tests for our library, the code in Listing
15-23 will compile without any errors, but the test will fail:
$ cargo test
Compiling limit-tracker v0.1.0 (file:///projects/limit-tracker)
Finished test [unoptimized + debuginfo] target(s) in 0.91s
Running unittests src/lib.rs (target/debug/deps/limit_tracker-e599811fa246dbde)
running 1 test
test tests::it_sends_an_over_75_percent_warning_message ... FAILED
failures:
---- tests::it_sends_an_over_75_percent_warning_message stdout ----
thread 'tests::it_sends_an_over_75_percent_warning_message' panicked at 'already borrowed: BorrowMutError', src/lib.rs:60:53
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::it_sends_an_over_75_percent_warning_message
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `--lib`
Notice that the code panicked with the message already borrowed: BorrowMutError
. This is how RefCell<T>
handles violations of the borrowing
rules at runtime.
Choosing to catch borrowing errors at runtime rather than compile time, as
we’ve done here, means you’d potentially be finding mistakes in your code later
in the development process: possibly not until your code was deployed to
production. Also, your code would incur a small runtime performance penalty as
a result of keeping track of the borrows at runtime rather than compile time.
However, using RefCell<T>
makes it possible to write a mock object that can
modify itself to keep track of the messages it has seen while you’re using it
in a context where only immutable values are allowed. You can use RefCell<T>
despite its trade-offs to get more functionality than regular references
provide.
Having Multiple Owners of Mutable Data by Combining Rc<T>
and RefCell<T>
A common way to use RefCell<T>
is in combination with Rc<T>
. Recall that
Rc<T>
lets you have multiple owners of some data, but it only gives immutable
access to that data. If you have an Rc<T>
that holds a RefCell<T>
, you can
get a value that can have multiple owners and that you can mutate!
For example, recall the cons list example in Listing 15-18 where we used
Rc<T>
to allow multiple lists to share ownership of another list. Because
Rc<T>
holds only immutable values, we can’t change any of the values in the
list once we’ve created them. Let’s add in RefCell<T>
to gain the ability to
change the values in the lists. Listing 15-24 shows that by using a
RefCell<T>
in the Cons
definition, we can modify the value stored in all
the lists:
Filename: src/main.rs
#[derive(Debug)] enum List { Cons(Rc<RefCell<i32>>, Rc<List>), Nil, } use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; fn main() { let value = Rc::new(RefCell::new(5)); let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a)); let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a)); *value.borrow_mut() += 10; println!("a after = {:?}", a); println!("b after = {:?}", b); println!("c after = {:?}", c); }
We create a value that is an instance of Rc<RefCell<i32>>
and store it in a
variable named value
so we can access it directly later. Then we create a
List
in a
with a Cons
variant that holds value
. We need to clone
value
so both a
and value
have ownership of the inner 5
value rather
than transferring ownership from value
to a
or having a
borrow from
value
.
We wrap the list a
in an Rc<T>
so when we create lists b
and c
, they
can both refer to a
, which is what we did in Listing 15-18.
After we’ve created the lists in a
, b
, and c
, we want to add 10 to the
value in value
. We do this by calling borrow_mut
on value
, which uses the
automatic dereferencing feature we discussed in Chapter 5 (see the section
“Where’s the ->
Operator?”) to
dereference the Rc<T>
to the inner RefCell<T>
value. The borrow_mut
method returns a RefMut<T>
smart pointer, and we use the dereference operator
on it and change the inner value.
When we print a
, b
, and c
, we can see that they all have the modified
value of 15 rather than 5:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished dev [unoptimized + debuginfo] target(s) in 0.63s
Running `target/debug/cons-list`
a after = Cons(RefCell { value: 15 }, Nil)
b after = Cons(RefCell { value: 3 }, Cons(RefCell { value: 15 }, Nil))
c after = Cons(RefCell { value: 4 }, Cons(RefCell { value: 15 }, Nil))
This technique is pretty neat! By using RefCell<T>
, we have an outwardly
immutable List
value. But we can use the methods on RefCell<T>
that provide
access to its interior mutability so we can modify our data when we need to.
The runtime checks of the borrowing rules protect us from data races, and it’s
sometimes worth trading a bit of speed for this flexibility in our data
structures. Note that RefCell<T>
does not work for multithreaded code!
Mutex<T>
is the thread-safe version of RefCell<T>
and we’ll discuss
Mutex<T>
in Chapter 16.
Reference Cycles Can Leak Memory
Rust’s memory safety guarantees make it difficult, but not impossible, to
accidentally create memory that is never cleaned up (known as a memory leak).
Preventing memory leaks entirely is not one of Rust’s guarantees, meaning
memory leaks are memory safe in Rust. We can see that Rust allows memory leaks
by using Rc<T>
and RefCell<T>
: it’s possible to create references where
items refer to each other in a cycle. This creates memory leaks because the
reference count of each item in the cycle will never reach 0, and the values
will never be dropped.
Creating a Reference Cycle
Let’s look at how a reference cycle might happen and how to prevent it,
starting with the definition of the List
enum and a tail
method in Listing
15-25:
Filename: src/main.rs
use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] enum List { Cons(i32, RefCell<Rc<List>>), Nil, } impl List { fn tail(&self) -> Option<&RefCell<Rc<List>>> { match self { Cons(_, item) => Some(item), Nil => None, } } } fn main() {}
We’re using another variation of the List
definition from Listing 15-5. The
second element in the Cons
variant is now RefCell<Rc<List>>
, meaning that
instead of having the ability to modify the i32
value as we did in Listing
15-24, we want to modify the List
value a Cons
variant is pointing to.
We’re also adding a tail
method to make it convenient for us to access the
second item if we have a Cons
variant.
In Listing 15-26, we’re adding a main
function that uses the definitions in
Listing 15-25. This code creates a list in a
and a list in b
that points to
the list in a
. Then it modifies the list in a
to point to b
, creating a
reference cycle. There are println!
statements along the way to show what the
reference counts are at various points in this process.
Filename: src/main.rs
use crate::List::{Cons, Nil}; use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] enum List { Cons(i32, RefCell<Rc<List>>), Nil, } impl List { fn tail(&self) -> Option<&RefCell<Rc<List>>> { match self { Cons(_, item) => Some(item), Nil => None, } } } fn main() { let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); println!("a initial rc count = {}", Rc::strong_count(&a)); println!("a next item = {:?}", a.tail()); let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); println!("a rc count after b creation = {}", Rc::strong_count(&a)); println!("b initial rc count = {}", Rc::strong_count(&b)); println!("b next item = {:?}", b.tail()); if let Some(link) = a.tail() { *link.borrow_mut() = Rc::clone(&b); } println!("b rc count after changing a = {}", Rc::strong_count(&b)); println!("a rc count after changing a = {}", Rc::strong_count(&a)); // Uncomment the next line to see that we have a cycle; // it will overflow the stack // println!("a next item = {:?}", a.tail()); }
We create an Rc<List>
instance holding a List
value in the variable a
with an initial list of 5, Nil
. We then create an Rc<List>
instance holding
another List
value in the variable b
that contains the value 10 and points
to the list in a
.
We modify a
so it points to b
instead of Nil
, creating a cycle. We do
that by using the tail
method to get a reference to the RefCell<Rc<List>>
in a
, which we put in the variable link
. Then we use the borrow_mut
method on the RefCell<Rc<List>>
to change the value inside from an Rc<List>
that holds a Nil
value to the Rc<List>
in b
.
When we run this code, keeping the last println!
commented out for the
moment, we’ll get this output:
$ cargo run
Compiling cons-list v0.1.0 (file:///projects/cons-list)
Finished dev [unoptimized + debuginfo] target(s) in 0.53s
Running `target/debug/cons-list`
a initial rc count = 1
a next item = Some(RefCell { value: Nil })
a rc count after b creation = 2
b initial rc count = 1
b next item = Some(RefCell { value: Cons(5, RefCell { value: Nil }) })
b rc count after changing a = 2
a rc count after changing a = 2
The reference count of the Rc<List>
instances in both a
and b
are 2 after
we change the list in a
to point to b
. At the end of main
, Rust drops the
variable b
, which decreases the reference count of the b
Rc<List>
instance
from 2 to 1. The memory that Rc<List>
has on the heap won’t be dropped at
this point, because its reference count is 1, not 0. Then Rust drops a
, which
decreases the reference count of the a
Rc<List>
instance from 2 to 1 as
well. This instance’s memory can’t be dropped either, because the other
Rc<List>
instance still refers to it. The memory allocated to the list will
remain uncollected forever. To visualize this reference cycle, we’ve created a
diagram in Figure 15-4.
If you uncomment the last println!
and run the program, Rust will try to
print this cycle with a
pointing to b
pointing to a
and so forth until it
overflows the stack.
Compared to a real-world program, the consequences of creating a reference cycle in this example aren’t very dire: right after we create the reference cycle, the program ends. However, if a more complex program allocated lots of memory in a cycle and held onto it for a long time, the program would use more memory than it needed and might overwhelm the system, causing it to run out of available memory.
Creating reference cycles is not easily done, but it’s not impossible either.
If you have RefCell<T>
values that contain Rc<T>
values or similar nested
combinations of types with interior mutability and reference counting, you must
ensure that you don’t create cycles; you can’t rely on Rust to catch them.
Creating a reference cycle would be a logic bug in your program that you should
use automated tests, code reviews, and other software development practices to
minimize.
Another solution for avoiding reference cycles is reorganizing your data
structures so that some references express ownership and some references don’t.
As a result, you can have cycles made up of some ownership relationships and
some non-ownership relationships, and only the ownership relationships affect
whether or not a value can be dropped. In Listing 15-25, we always want Cons
variants to own their list, so reorganizing the data structure isn’t possible.
Let’s look at an example using graphs made up of parent nodes and child nodes
to see when non-ownership relationships are an appropriate way to prevent
reference cycles.
Preventing Reference Cycles: Turning an Rc<T>
into a Weak<T>
So far, we’ve demonstrated that calling Rc::clone
increases the
strong_count
of an Rc<T>
instance, and an Rc<T>
instance is only cleaned
up if its strong_count
is 0. You can also create a weak reference to the
value within an Rc<T>
instance by calling Rc::downgrade
and passing a
reference to the Rc<T>
. Strong references are how you can share ownership of
an Rc<T>
instance. Weak references don’t express an ownership relationship,
and their count doesn’t affect when an Rc<T>
instance is cleaned up. They
won’t cause a reference cycle because any cycle involving some weak references
will be broken once the strong reference count of values involved is 0.
When you call Rc::downgrade
, you get a smart pointer of type Weak<T>
.
Instead of increasing the strong_count
in the Rc<T>
instance by 1, calling
Rc::downgrade
increases the weak_count
by 1. The Rc<T>
type uses
weak_count
to keep track of how many Weak<T>
references exist, similar to
strong_count
. The difference is the weak_count
doesn’t need to be 0 for the
Rc<T>
instance to be cleaned up.
Because the value that Weak<T>
references might have been dropped, to do
anything with the value that a Weak<T>
is pointing to, you must make sure the
value still exists. Do this by calling the upgrade
method on a Weak<T>
instance, which will return an Option<Rc<T>>
. You’ll get a result of Some
if the Rc<T>
value has not been dropped yet and a result of None
if the
Rc<T>
value has been dropped. Because upgrade
returns an Option<Rc<T>>
,
Rust will ensure that the Some
case and the None
case are handled, and
there won’t be an invalid pointer.
As an example, rather than using a list whose items know only about the next item, we’ll create a tree whose items know about their children items and their parent items.
Creating a Tree Data Structure: a Node
with Child Nodes
To start, we’ll build a tree with nodes that know about their child nodes.
We’ll create a struct named Node
that holds its own i32
value as well as
references to its children Node
values:
Filename: src/main.rs
use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] struct Node { value: i32, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, children: RefCell::new(vec![]), }); let branch = Rc::new(Node { value: 5, children: RefCell::new(vec![Rc::clone(&leaf)]), }); }
We want a Node
to own its children, and we want to share that ownership with
variables so we can access each Node
in the tree directly. To do this, we
define the Vec<T>
items to be values of type Rc<Node>
. We also want to
modify which nodes are children of another node, so we have a RefCell<T>
in
children
around the Vec<Rc<Node>>
.
Next, we’ll use our struct definition and create one Node
instance named
leaf
with the value 3 and no children, and another instance named branch
with the value 5 and leaf
as one of its children, as shown in Listing 15-27:
Filename: src/main.rs
use std::cell::RefCell; use std::rc::Rc; #[derive(Debug)] struct Node { value: i32, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, children: RefCell::new(vec![]), }); let branch = Rc::new(Node { value: 5, children: RefCell::new(vec![Rc::clone(&leaf)]), }); }
We clone the Rc<Node>
in leaf
and store that in branch
, meaning the
Node
in leaf
now has two owners: leaf
and branch
. We can get from
branch
to leaf
through branch.children
, but there’s no way to get from
leaf
to branch
. The reason is that leaf
has no reference to branch
and
doesn’t know they’re related. We want leaf
to know that branch
is its
parent. We’ll do that next.
Adding a Reference from a Child to Its Parent
To make the child node aware of its parent, we need to add a parent
field to
our Node
struct definition. The trouble is in deciding what the type of
parent
should be. We know it can’t contain an Rc<T>
, because that would
create a reference cycle with leaf.parent
pointing to branch
and
branch.children
pointing to leaf
, which would cause their strong_count
values to never be 0.
Thinking about the relationships another way, a parent node should own its children: if a parent node is dropped, its child nodes should be dropped as well. However, a child should not own its parent: if we drop a child node, the parent should still exist. This is a case for weak references!
So instead of Rc<T>
, we’ll make the type of parent
use Weak<T>
,
specifically a RefCell<Weak<Node>>
. Now our Node
struct definition looks
like this:
Filename: src/main.rs
use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); }
A node will be able to refer to its parent node but doesn’t own its parent.
In Listing 15-28, we update main
to use this new definition so the leaf
node will have a way to refer to its parent, branch
:
Filename: src/main.rs
use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); }
Creating the leaf
node looks similar to Listing 15-27 with the exception of
the parent
field: leaf
starts out without a parent, so we create a new,
empty Weak<Node>
reference instance.
At this point, when we try to get a reference to the parent of leaf
by using
the upgrade
method, we get a None
value. We see this in the output from the
first println!
statement:
leaf parent = None
When we create the branch
node, it will also have a new Weak<Node>
reference in the parent
field, because branch
doesn’t have a parent node.
We still have leaf
as one of the children of branch
. Once we have the
Node
instance in branch
, we can modify leaf
to give it a Weak<Node>
reference to its parent. We use the borrow_mut
method on the
RefCell<Weak<Node>>
in the parent
field of leaf
, and then we use the
Rc::downgrade
function to create a Weak<Node>
reference to branch
from
the Rc<Node>
in branch.
When we print the parent of leaf
again, this time we’ll get a Some
variant
holding branch
: now leaf
can access its parent! When we print leaf
, we
also avoid the cycle that eventually ended in a stack overflow like we had in
Listing 15-26; the Weak<Node>
references are printed as (Weak)
:
leaf parent = Some(Node { value: 5, parent: RefCell { value: (Weak) },
children: RefCell { value: [Node { value: 3, parent: RefCell { value: (Weak) },
children: RefCell { value: [] } }] } })
The lack of infinite output indicates that this code didn’t create a reference
cycle. We can also tell this by looking at the values we get from calling
Rc::strong_count
and Rc::weak_count
.
Visualizing Changes to strong_count
and weak_count
Let’s look at how the strong_count
and weak_count
values of the Rc<Node>
instances change by creating a new inner scope and moving the creation of
branch
into that scope. By doing so, we can see what happens when branch
is
created and then dropped when it goes out of scope. The modifications are shown
in Listing 15-29:
Filename: src/main.rs
use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: RefCell<Vec<Rc<Node>>>, } fn main() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]), }); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); { let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: RefCell::new(vec![Rc::clone(&leaf)]), }); *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!( "branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch), ); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); } println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); }
After leaf
is created, its Rc<Node>
has a strong count of 1 and a weak
count of 0. In the inner scope, we create branch
and associate it with
leaf
, at which point when we print the counts, the Rc<Node>
in branch
will have a strong count of 1 and a weak count of 1 (for leaf.parent
pointing
to branch
with a Weak<Node>
). When we print the counts in leaf
, we’ll see
it will have a strong count of 2, because branch
now has a clone of the
Rc<Node>
of leaf
stored in branch.children
, but will still have a weak
count of 0.
When the inner scope ends, branch
goes out of scope and the strong count of
the Rc<Node>
decreases to 0, so its Node
is dropped. The weak count of 1
from leaf.parent
has no bearing on whether or not Node
is dropped, so we
don’t get any memory leaks!
If we try to access the parent of leaf
after the end of the scope, we’ll get
None
again. At the end of the program, the Rc<Node>
in leaf
has a strong
count of 1 and a weak count of 0, because the variable leaf
is now the only
reference to the Rc<Node>
again.
All of the logic that manages the counts and value dropping is built into
Rc<T>
and Weak<T>
and their implementations of the Drop
trait. By
specifying that the relationship from a child to its parent should be a
Weak<T>
reference in the definition of Node
, you’re able to have parent
nodes point to child nodes and vice versa without creating a reference cycle
and memory leaks.
Summary
This chapter covered how to use smart pointers to make different guarantees and
trade-offs from those Rust makes by default with regular references. The
Box<T>
type has a known size and points to data allocated on the heap. The
Rc<T>
type keeps track of the number of references to data on the heap so
that data can have multiple owners. The RefCell<T>
type with its interior
mutability gives us a type that we can use when we need an immutable type but
need to change an inner value of that type; it also enforces the borrowing
rules at runtime instead of at compile time.
Also discussed were the Deref
and Drop
traits, which enable a lot of the
functionality of smart pointers. We explored reference cycles that can cause
memory leaks and how to prevent them using Weak<T>
.
If this chapter has piqued your interest and you want to implement your own smart pointers, check out “The Rustonomicon” for more useful information.
Next, we’ll talk about concurrency in Rust. You’ll even learn about a few new smart pointers.
Fearless Concurrency
Handling concurrent programming safely and efficiently is another of Rust’s major goals. Concurrent programming, where different parts of a program execute independently, and parallel programming, where different parts of a program execute at the same time, are becoming increasingly important as more computers take advantage of their multiple processors. Historically, programming in these contexts has been difficult and error prone: Rust hopes to change that.
Initially, the Rust team thought that ensuring memory safety and preventing concurrency problems were two separate challenges to be solved with different methods. Over time, the team discovered that the ownership and type systems are a powerful set of tools to help manage memory safety and concurrency problems! By leveraging ownership and type checking, many concurrency errors are compile-time errors in Rust rather than runtime errors. Therefore, rather than making you spend lots of time trying to reproduce the exact circumstances under which a runtime concurrency bug occurs, incorrect code will refuse to compile and present an error explaining the problem. As a result, you can fix your code while you’re working on it rather than potentially after it has been shipped to production. We’ve nicknamed this aspect of Rust fearless concurrency. Fearless concurrency allows you to write code that is free of subtle bugs and is easy to refactor without introducing new bugs.
Note: For simplicity’s sake, we’ll refer to many of the problems as concurrent rather than being more precise by saying concurrent and/or parallel. If this book were about concurrency and/or parallelism, we’d be more specific. For this chapter, please mentally substitute concurrent and/or parallel whenever we use concurrent.
Many languages are dogmatic about the solutions they offer for handling concurrent problems. For example, Erlang has elegant functionality for message-passing concurrency but has only obscure ways to share state between threads. Supporting only a subset of possible solutions is a reasonable strategy for higher-level languages, because a higher-level language promises benefits from giving up some control to gain abstractions. However, lower-level languages are expected to provide the solution with the best performance in any given situation and have fewer abstractions over the hardware. Therefore, Rust offers a variety of tools for modeling problems in whatever way is appropriate for your situation and requirements.
Here are the topics we’ll cover in this chapter:
- How to create threads to run multiple pieces of code at the same time
- Message-passing concurrency, where channels send messages between threads
- Shared-state concurrency, where multiple threads have access to some piece of data
- The
Sync
andSend
traits, which extend Rust’s concurrency guarantees to user-defined types as well as types provided by the standard library
Using Threads to Run Code Simultaneously
In most current operating systems, an executed program’s code is run in a process, and the operating system will manage multiple processes at once. Within a program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. For example, a web server could have multiple threads so that it could respond to more than one request at the same time.
Splitting the computation in your program into multiple threads to run multiple tasks at the same time can improve performance, but it also adds complexity. Because threads can run simultaneously, there’s no inherent guarantee about the order in which parts of your code on different threads will run. This can lead to problems, such as:
- Race conditions, where threads are accessing data or resources in an inconsistent order
- Deadlocks, where two threads are waiting for each other, preventing both threads from continuing
- Bugs that happen only in certain situations and are hard to reproduce and fix reliably
Rust attempts to mitigate the negative effects of using threads, but programming in a multithreaded context still takes careful thought and requires a code structure that is different from that in programs running in a single thread.
Programming languages implement threads in a few different ways, and many operating systems provide an API the language can call for creating new threads. The Rust standard library uses a 1:1 model of thread implementation, whereby a program uses one operating system thread per one language thread. There are crates that implement other models of threading that make different tradeoffs to the 1:1 model.
Creating a New Thread with spawn
To create a new thread, we call the thread::spawn
function and pass it a
closure (we talked about closures in Chapter 13) containing the code we want to
run in the new thread. The example in Listing 16-1 prints some text from a main
thread and other text from a new thread:
Filename: src/main.rs
use std::thread; use std::time::Duration; fn main() { thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } }
Note that when the main thread of a Rust program completes, all spawned threads are shut down, whether or not they have finished running. The output from this program might be a little different every time, but it will look similar to the following:
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
The calls to thread::sleep
force a thread to stop its execution for a short
duration, allowing a different thread to run. The threads will probably take
turns, but that isn’t guaranteed: it depends on how your operating system
schedules the threads. In this run, the main thread printed first, even though
the print statement from the spawned thread appears first in the code. And even
though we told the spawned thread to print until i
is 9, it only got to 5
before the main thread shut down.
If you run this code and only see output from the main thread, or don’t see any overlap, try increasing the numbers in the ranges to create more opportunities for the operating system to switch between the threads.
Waiting for All Threads to Finish Using join
Handles
The code in Listing 16-1 not only stops the spawned thread prematurely most of the time due to the main thread ending, but because there is no guarantee on the order in which threads run, we also can’t guarantee that the spawned thread will get to run at all!
We can fix the problem of the spawned thread not running or ending prematurely
by saving the return value of thread::spawn
in a variable. The return type of
thread::spawn
is JoinHandle
. A JoinHandle
is an owned value that, when we
call the join
method on it, will wait for its thread to finish. Listing 16-2
shows how to use the JoinHandle
of the thread we created in Listing 16-1 and
call join
to make sure the spawned thread finishes before main
exits:
Filename: src/main.rs
use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); }
Calling join
on the handle blocks the thread currently running until the
thread represented by the handle terminates. Blocking a thread means that
thread is prevented from performing work or exiting. Because we’ve put the call
to join
after the main thread’s for
loop, running Listing 16-2 should
produce output similar to this:
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 1 from the spawned thread!
hi number 3 from the main thread!
hi number 2 from the spawned thread!
hi number 4 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
The two threads continue alternating, but the main thread waits because of the
call to handle.join()
and does not end until the spawned thread is finished.
But let’s see what happens when we instead move handle.join()
before the
for
loop in main
, like this:
Filename: src/main.rs
use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hi number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); handle.join().unwrap(); for i in 1..5 { println!("hi number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } }
The main thread will wait for the spawned thread to finish and then run its
for
loop, so the output won’t be interleaved anymore, as shown here:
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
Small details, such as where join
is called, can affect whether or not your
threads run at the same time.
Using move
Closures with Threads
We'll often use the move
keyword with closures passed to thread::spawn
because the closure will then take ownership of the values it uses from the
environment, thus transferring ownership of those values from one thread to
another. In the “Capturing References or Moving Ownership” section of Chapter 13, we discussed move
in the context of closures. Now,
we’ll concentrate more on the interaction between move
and thread::spawn
.
Notice in Listing 16-1 that the closure we pass to thread::spawn
takes no
arguments: we’re not using any data from the main thread in the spawned
thread’s code. To use data from the main thread in the spawned thread, the
spawned thread’s closure must capture the values it needs. Listing 16-3 shows
an attempt to create a vector in the main thread and use it in the spawned
thread. However, this won’t yet work, as you’ll see in a moment.
Filename: src/main.rs
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
The closure uses v
, so it will capture v
and make it part of the closure’s
environment. Because thread::spawn
runs this closure in a new thread, we
should be able to access v
inside that new thread. But when we compile this
example, we get the following error:
$ cargo run
Compiling threads v0.1.0 (file:///projects/threads)
error[E0373]: closure may outlive the current function, but it borrows `v`, which is owned by the current function
--> src/main.rs:6:32
|
6 | let handle = thread::spawn(|| {
| ^^ may outlive borrowed value `v`
7 | println!("Here's a vector: {:?}", v);
| - `v` is borrowed here
|
note: function requires argument type to outlive `'static`
--> src/main.rs:6:18
|
6 | let handle = thread::spawn(|| {
| __________________^
7 | | println!("Here's a vector: {:?}", v);
8 | | });
| |______^
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
6 | let handle = thread::spawn(move || {
| ++++
For more information about this error, try `rustc --explain E0373`.
error: could not compile `threads` due to previous error
Rust infers how to capture v
, and because println!
only needs a reference
to v
, the closure tries to borrow v
. However, there’s a problem: Rust can’t
tell how long the spawned thread will run, so it doesn’t know if the reference
to v
will always be valid.
Listing 16-4 provides a scenario that’s more likely to have a reference to v
that won’t be valid:
Filename: src/main.rs
use std::thread;
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(|| {
println!("Here's a vector: {:?}", v);
});
drop(v); // oh no!
handle.join().unwrap();
}
If Rust allowed us to run this code, there’s a possibility the spawned thread
would be immediately put in the background without running at all. The spawned
thread has a reference to v
inside, but the main thread immediately drops
v
, using the drop
function we discussed in Chapter 15. Then, when the
spawned thread starts to execute, v
is no longer valid, so a reference to it
is also invalid. Oh no!
To fix the compiler error in Listing 16-3, we can use the error message’s advice:
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
6 | let handle = thread::spawn(move || {
| ++++
By adding the move
keyword before the closure, we force the closure to take
ownership of the values it’s using rather than allowing Rust to infer that it
should borrow the values. The modification to Listing 16-3 shown in Listing
16-5 will compile and run as we intend:
Filename: src/main.rs
use std::thread; fn main() { let v = vec![1, 2, 3]; let handle = thread::spawn(move || { println!("Here's a vector: {:?}", v); }); handle.join().unwrap(); }
We might be tempted to try the same thing to fix the code in Listing 16-4 where
the main thread called drop
by using a move
closure. However, this fix will
not work because what Listing 16-4 is trying to do is disallowed for a
different reason. If we added move
to the closure, we would move v
into the
closure’s environment, and we could no longer call drop
on it in the main
thread. We would get this compiler error instead:
$ cargo run
Compiling threads v0.1.0 (file:///projects/threads)
error[E0382]: use of moved value: `v`
--> src/main.rs:10:10
|
4 | let v = vec![1, 2, 3];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
5 |
6 | let handle = thread::spawn(move || {
| ------- value moved into closure here
7 | println!("Here's a vector: {:?}", v);
| - variable moved due to use in closure
...
10 | drop(v); // oh no!
| ^ value used here after move
For more information about this error, try `rustc --explain E0382`.
error: could not compile `threads` due to previous error
Rust’s ownership rules have saved us again! We got an error from the code in
Listing 16-3 because Rust was being conservative and only borrowing v
for the
thread, which meant the main thread could theoretically invalidate the spawned
thread’s reference. By telling Rust to move ownership of v
to the spawned
thread, we’re guaranteeing Rust that the main thread won’t use v
anymore. If
we change Listing 16-4 in the same way, we’re then violating the ownership
rules when we try to use v
in the main thread. The move
keyword overrides
Rust’s conservative default of borrowing; it doesn’t let us violate the
ownership rules.
With a basic understanding of threads and the thread API, let’s look at what we can do with threads.
Using Message Passing to Transfer Data Between Threads
One increasingly popular approach to ensuring safe concurrency is message passing, where threads or actors communicate by sending each other messages containing data. Here’s the idea in a slogan from the Go language documentation: “Do not communicate by sharing memory; instead, share memory by communicating.”
To accomplish message-sending concurrency, Rust's standard library provides an implementation of channels. A channel is a general programming concept by which data is sent from one thread to another.
You can imagine a channel in programming as being like a directional channel of water, such as a stream or a river. If you put something like a rubber duck into a river, it will travel downstream to the end of the waterway.
A channel has two halves: a transmitter and a receiver. The transmitter half is the upstream location where you put rubber ducks into the river, and the receiver half is where the rubber duck ends up downstream. One part of your code calls methods on the transmitter with the data you want to send, and another part checks the receiving end for arriving messages. A channel is said to be closed if either the transmitter or receiver half is dropped.
Here, we’ll work up to a program that has one thread to generate values and send them down a channel, and another thread that will receive the values and print them out. We’ll be sending simple values between threads using a channel to illustrate the feature. Once you’re familiar with the technique, you could use channels for any threads that need to communicate between each other, such as a chat system or a system where many threads perform parts of a calculation and send the parts to one thread that aggregates the results.
First, in Listing 16-6, we’ll create a channel but not do anything with it. Note that this won’t compile yet because Rust can’t tell what type of values we want to send over the channel.
Filename: src/main.rs
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
}
We create a new channel using the mpsc::channel
function; mpsc
stands for
multiple producer, single consumer. In short, the way Rust’s standard library
implements channels means a channel can have multiple sending ends that
produce values but only one receiving end that consumes those values. Imagine
multiple streams flowing together into one big river: everything sent down any
of the streams will end up in one river at the end. We’ll start with a single
producer for now, but we’ll add multiple producers when we get this example
working.
The mpsc::channel
function returns a tuple, the first element of which is the
sending end--the transmitter--and the second element is the receiving end--the
receiver. The abbreviations tx
and rx
are traditionally used in many fields
for transmitter and receiver respectively, so we name our variables as such
to indicate each end. We’re using a let
statement with a pattern that
destructures the tuples; we’ll discuss the use of patterns in let
statements
and destructuring in Chapter 18. For now, know that using a let
statement
this way is a convenient approach to extract the pieces of the tuple returned
by mpsc::channel
.
Let’s move the transmitting end into a spawned thread and have it send one string so the spawned thread is communicating with the main thread, as shown in Listing 16-7. This is like putting a rubber duck in the river upstream or sending a chat message from one thread to another.
Filename: src/main.rs
use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap(); }); }
Again, we’re using thread::spawn
to create a new thread and then using move
to move tx
into the closure so the spawned thread owns tx
. The spawned
thread needs to own the transmitter to be able to send messages through the
channel. The transmitter has a send
method that takes the value we want to
send. The send
method returns a Result<T, E>
type, so if the receiver has
already been dropped and there’s nowhere to send a value, the send operation
will return an error. In this example, we’re calling unwrap
to panic in case
of an error. But in a real application, we would handle it properly: return to
Chapter 9 to review strategies for proper error handling.
In Listing 16-8, we’ll get the value from the receiver in the main thread. This is like retrieving the rubber duck from the water at the end of the river or receiving a chat message.
Filename: src/main.rs
use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let val = String::from("hi"); tx.send(val).unwrap(); }); let received = rx.recv().unwrap(); println!("Got: {}", received); }
The receiver has two useful methods: recv
and try_recv
. We’re using recv
,
short for receive, which will block the main thread’s execution and wait
until a value is sent down the channel. Once a value is sent, recv
will
return it in a Result<T, E>
. When the transmitter closes, recv
will return
an error to signal that no more values will be coming.
The try_recv
method doesn’t block, but will instead return a Result<T, E>
immediately: an Ok
value holding a message if one is available and an Err
value if there aren’t any messages this time. Using try_recv
is useful if
this thread has other work to do while waiting for messages: we could write a
loop that calls try_recv
every so often, handles a message if one is
available, and otherwise does other work for a little while until checking
again.
We’ve used recv
in this example for simplicity; we don’t have any other work
for the main thread to do other than wait for messages, so blocking the main
thread is appropriate.
When we run the code in Listing 16-8, we’ll see the value printed from the main thread:
Got: hi
Perfect!
Channels and Ownership Transference
The ownership rules play a vital role in message sending because they help you
write safe, concurrent code. Preventing errors in concurrent programming is the
advantage of thinking about ownership throughout your Rust programs. Let’s do
an experiment to show how channels and ownership work together to prevent
problems: we’ll try to use a val
value in the spawned thread after we’ve
sent it down the channel. Try compiling the code in Listing 16-9 to see why
this code isn’t allowed:
Filename: src/main.rs
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
println!("val is {}", val);
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
Here, we try to print val
after we’ve sent it down the channel via tx.send
.
Allowing this would be a bad idea: once the value has been sent to another
thread, that thread could modify or drop it before we try to use the value
again. Potentially, the other thread’s modifications could cause errors or
unexpected results due to inconsistent or nonexistent data. However, Rust gives
us an error if we try to compile the code in Listing 16-9:
$ cargo run
Compiling message-passing v0.1.0 (file:///projects/message-passing)
error[E0382]: borrow of moved value: `val`
--> src/main.rs:10:31
|
8 | let val = String::from("hi");
| --- move occurs because `val` has type `String`, which does not implement the `Copy` trait
9 | tx.send(val).unwrap();
| --- value moved here
10 | println!("val is {}", val);
| ^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0382`.
error: could not compile `message-passing` due to previous error
Our concurrency mistake has caused a compile time error. The send
function
takes ownership of its parameter, and when the value is moved, the receiver
takes ownership of it. This stops us from accidentally using the value again
after sending it; the ownership system checks that everything is okay.
Sending Multiple Values and Seeing the Receiver Waiting
The code in Listing 16-8 compiled and ran, but it didn’t clearly show us that two separate threads were talking to each other over the channel. In Listing 16-10 we’ve made some modifications that will prove the code in Listing 16-8 is running concurrently: the spawned thread will now send multiple messages and pause for a second between each message.
Filename: src/main.rs
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}", received);
}
}
This time, the spawned thread has a vector of strings that we want to send to
the main thread. We iterate over them, sending each individually, and pause
between each by calling the thread::sleep
function with a Duration
value of
1 second.
In the main thread, we’re not calling the recv
function explicitly anymore:
instead, we’re treating rx
as an iterator. For each value received, we’re
printing it. When the channel is closed, iteration will end.
When running the code in Listing 16-10, you should see the following output with a 1-second pause in between each line:
Got: hi
Got: from
Got: the
Got: thread
Because we don’t have any code that pauses or delays in the for
loop in the
main thread, we can tell that the main thread is waiting to receive values from
the spawned thread.
Creating Multiple Producers by Cloning the Transmitter
Earlier we mentioned that mpsc
was an acronym for multiple producer,
single consumer. Let’s put mpsc
to use and expand the code in Listing 16-10
to create multiple threads that all send values to the same receiver. We can do
so by cloning the transmitter, as shown in Listing 16-11:
Filename: src/main.rs
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
// --snip--
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone();
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
];
for val in vals {
tx1.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
thread::spawn(move || {
let vals = vec![
String::from("more"),
String::from("messages"),
String::from("for"),
String::from("you"),
];
for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
for received in rx {
println!("Got: {}", received);
}
// --snip--
}
This time, before we create the first spawned thread, we call clone
on the
transmitter. This will give us a new transmitter we can pass to the first
spawned thread. We pass the original transmitter to a second spawned thread.
This gives us two threads, each sending different messages to the one receiver.
When you run the code, your output should look something like this:
Got: hi
Got: more
Got: from
Got: messages
Got: for
Got: the
Got: thread
Got: you
You might see the values in another order, depending on your system. This is
what makes concurrency interesting as well as difficult. If you experiment with
thread::sleep
, giving it various values in the different threads, each run
will be more nondeterministic and create different output each time.
Now that we’ve looked at how channels work, let’s look at a different method of concurrency.
Shared-State Concurrency
Message passing is a fine way of handling concurrency, but it’s not the only one. Another method would be for multiple threads to access the same shared data. Consider this part of the slogan from the Go language documentation again: “do not communicate by sharing memory.”
What would communicating by sharing memory look like? In addition, why would message-passing enthusiasts caution not to use memory sharing?
In a way, channels in any programming language are similar to single ownership, because once you transfer a value down a channel, you should no longer use that value. Shared memory concurrency is like multiple ownership: multiple threads can access the same memory location at the same time. As you saw in Chapter 15, where smart pointers made multiple ownership possible, multiple ownership can add complexity because these different owners need managing. Rust’s type system and ownership rules greatly assist in getting this management correct. For an example, let’s look at mutexes, one of the more common concurrency primitives for shared memory.
Using Mutexes to Allow Access to Data from One Thread at a Time
Mutex is an abbreviation for mutual exclusion, as in, a mutex allows only one thread to access some data at any given time. To access the data in a mutex, a thread must first signal that it wants access by asking to acquire the mutex’s lock. The lock is a data structure that is part of the mutex that keeps track of who currently has exclusive access to the data. Therefore, the mutex is described as guarding the data it holds via the locking system.
Mutexes have a reputation for being difficult to use because you have to remember two rules:
- You must attempt to acquire the lock before using the data.
- When you’re done with the data that the mutex guards, you must unlock the data so other threads can acquire the lock.
For a real-world metaphor for a mutex, imagine a panel discussion at a conference with only one microphone. Before a panelist can speak, they have to ask or signal that they want to use the microphone. When they get the microphone, they can talk for as long as they want to and then hand the microphone to the next panelist who requests to speak. If a panelist forgets to hand the microphone off when they’re finished with it, no one else is able to speak. If management of the shared microphone goes wrong, the panel won’t work as planned!
Management of mutexes can be incredibly tricky to get right, which is why so many people are enthusiastic about channels. However, thanks to Rust’s type system and ownership rules, you can’t get locking and unlocking wrong.
The API of Mutex<T>
As an example of how to use a mutex, let’s start by using a mutex in a single-threaded context, as shown in Listing 16-12:
Filename: src/main.rs
use std::sync::Mutex; fn main() { let m = Mutex::new(5); { let mut num = m.lock().unwrap(); *num = 6; } println!("m = {:?}", m); }
As with many types, we create a Mutex<T>
using the associated function new
.
To access the data inside the mutex, we use the lock
method to acquire the
lock. This call will block the current thread so it can’t do any work until
it’s our turn to have the lock.
The call to lock
would fail if another thread holding the lock panicked. In
that case, no one would ever be able to get the lock, so we’ve chosen to
unwrap
and have this thread panic if we’re in that situation.
After we’ve acquired the lock, we can treat the return value, named num
in
this case, as a mutable reference to the data inside. The type system ensures
that we acquire a lock before using the value in m
. The type of m
is
Mutex<i32>
, not i32
, so we must call lock
to be able to use the i32
value. We can’t forget; the type system won’t let us access the inner i32
otherwise.
As you might suspect, Mutex<T>
is a smart pointer. More accurately, the call
to lock
returns a smart pointer called MutexGuard
, wrapped in a
LockResult
that we handled with the call to unwrap
. The MutexGuard
smart
pointer implements Deref
to point at our inner data; the smart pointer also
has a Drop
implementation that releases the lock automatically when a
MutexGuard
goes out of scope, which happens at the end of the inner scope. As
a result, we don’t risk forgetting to release the lock and blocking the mutex
from being used by other threads, because the lock release happens
automatically.
After dropping the lock, we can print the mutex value and see that we were able
to change the inner i32
to 6.
Sharing a Mutex<T>
Between Multiple Threads
Now, let’s try to share a value between multiple threads using Mutex<T>
.
We’ll spin up 10 threads and have them each increment a counter value by 1, so
the counter goes from 0 to 10. The next example in Listing 16-13 will have
a compiler error, and we’ll use that error to learn more about using
Mutex<T>
and how Rust helps us use it correctly.
Filename: src/main.rs
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
We create a counter
variable to hold an i32
inside a Mutex<T>
, as we did
in Listing 16-12. Next, we create 10 threads by iterating over a range of
numbers. We use thread::spawn
and give all the threads the same closure: one
that moves the counter into the thread, acquires a lock on the Mutex<T>
by
calling the lock
method, and then adds 1 to the value in the mutex. When a
thread finishes running its closure, num
will go out of scope and release the
lock so another thread can acquire it.
In the main thread, we collect all the join handles. Then, as we did in Listing
16-2, we call join
on each handle to make sure all the threads finish. At
that point, the main thread will acquire the lock and print the result of this
program.
We hinted that this example wouldn’t compile. Now let’s find out why!
$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0382]: use of moved value: `counter`
--> src/main.rs:9:36
|
5 | let counter = Mutex::new(0);
| ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait
...
9 | let handle = thread::spawn(move || {
| ^^^^^^^ value moved into closure here, in previous iteration of loop
10 | let mut num = counter.lock().unwrap();
| ------- use occurs due to use in closure
For more information about this error, try `rustc --explain E0382`.
error: could not compile `shared-state` due to previous error
The error message states that the counter
value was moved in the previous
iteration of the loop. Rust is telling us that we can’t move the ownership
of lock counter
into multiple threads. Let’s fix the compiler error with a
multiple-ownership method we discussed in Chapter 15.
Multiple Ownership with Multiple Threads
In Chapter 15, we gave a value multiple owners by using the smart pointer
Rc<T>
to create a reference counted value. Let’s do the same here and see
what happens. We’ll wrap the Mutex<T>
in Rc<T>
in Listing 16-14 and clone
the Rc<T>
before moving ownership to the thread.
Filename: src/main.rs
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Rc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Rc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
Once again, we compile and get... different errors! The compiler is teaching us a lot.
$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely
--> src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ------------- ^------
| | |
| ______________________|_____________within this `[closure@src/main.rs:11:36: 11:43]`
| | |
| | required by a bound introduced by this call
12 | | let mut num = counter.lock().unwrap();
13 | |
14 | | *num += 1;
15 | | });
| |_________^ `Rc<Mutex<i32>>` cannot be sent between threads safely
|
= help: within `[closure@src/main.rs:11:36: 11:43]`, the trait `Send` is not implemented for `Rc<Mutex<i32>>`
note: required because it's used within this closure
--> src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:704:8
|
= note: required by this bound in `spawn`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `shared-state` due to previous error
Wow, that error message is very wordy! Here’s the important part to focus on:
`Rc<Mutex<i32>>` cannot be sent between threads safely
. The compiler is
also telling us the reason why: the trait `Send` is not implemented for `Rc<Mutex<i32>>`
. We’ll talk about Send
in the next section: it’s one of
the traits that ensures the types we use with threads are meant for use in
concurrent situations.
Unfortunately, Rc<T>
is not safe to share across threads. When Rc<T>
manages the reference count, it adds to the count for each call to clone
and
subtracts from the count when each clone is dropped. But it doesn’t use any
concurrency primitives to make sure that changes to the count can’t be
interrupted by another thread. This could lead to wrong counts—subtle bugs that
could in turn lead to memory leaks or a value being dropped before we’re done
with it. What we need is a type exactly like Rc<T>
but one that makes changes
to the reference count in a thread-safe way.
Atomic Reference Counting with Arc<T>
Fortunately, Arc<T>
is a type like Rc<T>
that is safe to use in
concurrent situations. The a stands for atomic, meaning it’s an atomically
reference counted type. Atomics are an additional kind of concurrency
primitive that we won’t cover in detail here: see the standard library
documentation for std::sync::atomic
for more
details. At this point, you just need to know that atomics work like primitive
types but are safe to share across threads.
You might then wonder why all primitive types aren’t atomic and why standard
library types aren’t implemented to use Arc<T>
by default. The reason is that
thread safety comes with a performance penalty that you only want to pay when
you really need to. If you’re just performing operations on values within a
single thread, your code can run faster if it doesn’t have to enforce the
guarantees atomics provide.
Let’s return to our example: Arc<T>
and Rc<T>
have the same API, so we fix
our program by changing the use
line, the call to new
, and the call to
clone
. The code in Listing 16-15 will finally compile and run:
Filename: src/main.rs
use std::sync::{Arc, Mutex}; use std::thread; fn main() { let counter = Arc::new(Mutex::new(0)); let mut handles = vec![]; for _ in 0..10 { let counter = Arc::clone(&counter); let handle = thread::spawn(move || { let mut num = counter.lock().unwrap(); *num += 1; }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } println!("Result: {}", *counter.lock().unwrap()); }
This code will print the following:
Result: 10
We did it! We counted from 0 to 10, which may not seem very impressive, but it
did teach us a lot about Mutex<T>
and thread safety. You could also use this
program’s structure to do more complicated operations than just incrementing a
counter. Using this strategy, you can divide a calculation into independent
parts, split those parts across threads, and then use a Mutex<T>
to have each
thread update the final result with its part.
Note that if you are doing simple numerical operations, there are types simpler
than Mutex<T>
types provided by the std::sync::atomic
module of the
standard library. These types provide safe, concurrent,
atomic access to primitive types. We chose to use Mutex<T>
with a primitive
type for this example so we could concentrate on how Mutex<T>
works.
Similarities Between RefCell<T>
/Rc<T>
and Mutex<T>
/Arc<T>
You might have noticed that counter
is immutable but we could get a mutable
reference to the value inside it; this means Mutex<T>
provides interior
mutability, as the Cell
family does. In the same way we used RefCell<T>
in
Chapter 15 to allow us to mutate contents inside an Rc<T>
, we use Mutex<T>
to mutate contents inside an Arc<T>
.
Another detail to note is that Rust can’t protect you from all kinds of logic
errors when you use Mutex<T>
. Recall in Chapter 15 that using Rc<T>
came
with the risk of creating reference cycles, where two Rc<T>
values refer to
each other, causing memory leaks. Similarly, Mutex<T>
comes with the risk of
creating deadlocks. These occur when an operation needs to lock two resources
and two threads have each acquired one of the locks, causing them to wait for
each other forever. If you’re interested in deadlocks, try creating a Rust
program that has a deadlock; then research deadlock mitigation strategies for
mutexes in any language and have a go at implementing them in Rust. The
standard library API documentation for Mutex<T>
and MutexGuard
offers
useful information.
We’ll round out this chapter by talking about the Send
and Sync
traits and
how we can use them with custom types.
Extensible Concurrency with the Sync
and Send
Traits
Interestingly, the Rust language has very few concurrency features. Almost every concurrency feature we’ve talked about so far in this chapter has been part of the standard library, not the language. Your options for handling concurrency are not limited to the language or the standard library; you can write your own concurrency features or use those written by others.
However, two concurrency concepts are embedded in the language: the
std::marker
traits Sync
and Send
.
Allowing Transference of Ownership Between Threads with Send
The Send
marker trait indicates that ownership of values of the type
implementing Send
can be transferred between threads. Almost every Rust type
is Send
, but there are some exceptions, including Rc<T>
: this cannot be
Send
because if you cloned an Rc<T>
value and tried to transfer ownership
of the clone to another thread, both threads might update the reference count
at the same time. For this reason, Rc<T>
is implemented for use in
single-threaded situations where you don’t want to pay the thread-safe
performance penalty.
Therefore, Rust’s type system and trait bounds ensure that you can never
accidentally send an Rc<T>
value across threads unsafely. When we tried to do
this in Listing 16-14, we got the error the trait Send is not implemented for Rc<Mutex<i32>>
. When we switched to Arc<T>
, which is Send
, the code
compiled.
Any type composed entirely of Send
types is automatically marked as Send
as
well. Almost all primitive types are Send
, aside from raw pointers, which
we’ll discuss in Chapter 19.
Allowing Access from Multiple Threads with Sync
The Sync
marker trait indicates that it is safe for the type implementing
Sync
to be referenced from multiple threads. In other words, any type T
is
Sync
if &T
(an immutable reference to T
) is Send
, meaning the reference
can be sent safely to another thread. Similar to Send
, primitive types are
Sync
, and types composed entirely of types that are Sync
are also Sync
.
The smart pointer Rc<T>
is also not Sync
for the same reasons that it’s not
Send
. The RefCell<T>
type (which we talked about in Chapter 15) and the
family of related Cell<T>
types are not Sync
. The implementation of borrow
checking that RefCell<T>
does at runtime is not thread-safe. The smart
pointer Mutex<T>
is Sync
and can be used to share access with multiple
threads as you saw in the “Sharing a Mutex<T>
Between Multiple
Threads” section.
Implementing Send
and Sync
Manually Is Unsafe
Because types that are made up of Send
and Sync
traits are automatically
also Send
and Sync
, we don’t have to implement those traits manually. As
marker traits, they don’t even have any methods to implement. They’re just
useful for enforcing invariants related to concurrency.
Manually implementing these traits involves implementing unsafe Rust code.
We’ll talk about using unsafe Rust code in Chapter 19; for now, the important
information is that building new concurrent types not made up of Send
and
Sync
parts requires careful thought to uphold the safety guarantees. “The
Rustonomicon” has more information about these guarantees and how to
uphold them.
Summary
This isn’t the last you’ll see of concurrency in this book: the project in Chapter 20 will use the concepts in this chapter in a more realistic situation than the smaller examples discussed here.
As mentioned earlier, because very little of how Rust handles concurrency is part of the language, many concurrency solutions are implemented as crates. These evolve more quickly than the standard library, so be sure to search online for the current, state-of-the-art crates to use in multithreaded situations.
The Rust standard library provides channels for message passing and smart
pointer types, such as Mutex<T>
and Arc<T>
, that are safe to use in
concurrent contexts. The type system and the borrow checker ensure that the
code using these solutions won’t end up with data races or invalid references.
Once you get your code to compile, you can rest assured that it will happily
run on multiple threads without the kinds of hard-to-track-down bugs common in
other languages. Concurrent programming is no longer a concept to be afraid of:
go forth and make your programs concurrent, fearlessly!
Next, we’ll talk about idiomatic ways to model problems and structure solutions as your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms relate to those you might be familiar with from object-oriented programming.
Object-Oriented Programming Features of Rust
Object-oriented programming (OOP) is a way of modeling programs. Objects as a programmatic concept were introduced in the programming language Simula in the 1960s. Those objects influenced Alan Kay’s programming architecture in which objects pass messages to each other. To describe this architecture, he coined the term object-oriented programming in 1967. Many competing definitions describe what OOP is, and by some of these definitions Rust is object-oriented, but by others it is not. In this chapter, we’ll explore certain characteristics that are commonly considered object-oriented and how those characteristics translate to idiomatic Rust. We’ll then show you how to implement an object-oriented design pattern in Rust and discuss the trade-offs of doing so versus implementing a solution using some of Rust’s strengths instead.
Characteristics of Object-Oriented Languages
There is no consensus in the programming community about what features a language must have to be considered object-oriented. Rust is influenced by many programming paradigms, including OOP; for example, we explored the features that came from functional programming in Chapter 13. Arguably, OOP languages share certain common characteristics, namely objects, encapsulation, and inheritance. Let’s look at what each of those characteristics means and whether Rust supports it.
Objects Contain Data and Behavior
The book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional, 1994), colloquially referred to as The Gang of Four book, is a catalog of object-oriented design patterns. It defines OOP this way:
Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations.
Using this definition, Rust is object-oriented: structs and enums have data,
and impl
blocks provide methods on structs and enums. Even though structs and
enums with methods aren’t called objects, they provide the same
functionality, according to the Gang of Four’s definition of objects.
Encapsulation that Hides Implementation Details
Another aspect commonly associated with OOP is the idea of encapsulation, which means that the implementation details of an object aren’t accessible to code using that object. Therefore, the only way to interact with an object is through its public API; code using the object shouldn’t be able to reach into the object’s internals and change data or behavior directly. This enables the programmer to change and refactor an object’s internals without needing to change the code that uses the object.
We discussed how to control encapsulation in Chapter 7: we can use the pub
keyword to decide which modules, types, functions, and methods in our code
should be public, and by default everything else is private. For example, we
can define a struct AveragedCollection
that has a field containing a vector
of i32
values. The struct can also have a field that contains the average of
the values in the vector, meaning the average doesn’t have to be computed
on demand whenever anyone needs it. In other words, AveragedCollection
will
cache the calculated average for us. Listing 17-1 has the definition of the
AveragedCollection
struct:
Filename: src/lib.rs
pub struct AveragedCollection {
list: Vec<i32>,
average: f64,
}
The struct is marked pub
so that other code can use it, but the fields within
the struct remain private. This is important in this case because we want to
ensure that whenever a value is added or removed from the list, the average is
also updated. We do this by implementing add
, remove
, and average
methods
on the struct, as shown in Listing 17-2:
Filename: src/lib.rs
pub struct AveragedCollection {
list: Vec<i32>,
average: f64,
}
impl AveragedCollection {
pub fn add(&mut self, value: i32) {
self.list.push(value);
self.update_average();
}
pub fn remove(&mut self) -> Option<i32> {
let result = self.list.pop();
match result {
Some(value) => {
self.update_average();
Some(value)
}
None => None,
}
}
pub fn average(&self) -> f64 {
self.average
}
fn update_average(&mut self) {
let total: i32 = self.list.iter().sum();
self.average = total as f64 / self.list.len() as f64;
}
}
The public methods add
, remove
, and average
are the only ways to access
or modify data in an instance of AveragedCollection
. When an item is added
to list
using the add
method or removed using the remove
method, the
implementations of each call the private update_average
method that handles
updating the average
field as well.
We leave the list
and average
fields private so there is no way for
external code to add or remove items to or from the list
field directly;
otherwise, the average
field might become out of sync when the list
changes. The average
method returns the value in the average
field,
allowing external code to read the average
but not modify it.
Because we’ve encapsulated the implementation details of the struct
AveragedCollection
, we can easily change aspects, such as the data structure,
in the future. For instance, we could use a HashSet<i32>
instead of a
Vec<i32>
for the list
field. As long as the signatures of the add
,
remove
, and average
public methods stay the same, code using
AveragedCollection
wouldn’t need to change. If we made list
public instead,
this wouldn’t necessarily be the case: HashSet<i32>
and Vec<i32>
have
different methods for adding and removing items, so the external code would
likely have to change if it were modifying list
directly.
If encapsulation is a required aspect for a language to be considered
object-oriented, then Rust meets that requirement. The option to use pub
or
not for different parts of code enables encapsulation of implementation details.
Inheritance as a Type System and as Code Sharing
Inheritance is a mechanism whereby an object can inherit elements from another object’s definition, thus gaining the parent object’s data and behavior without you having to define them again.
If a language must have inheritance to be an object-oriented language, then Rust is not one. There is no way to define a struct that inherits the parent struct’s fields and method implementations without using a macro.
However, if you’re used to having inheritance in your programming toolbox, you can use other solutions in Rust, depending on your reason for reaching for inheritance in the first place.
You would choose inheritance for two main reasons. One is for reuse of code:
you can implement particular behavior for one type, and inheritance enables you
to reuse that implementation for a different type. You can do this in a limited
way in Rust code using default trait method implementations, which you saw in
Listing 10-14 when we added a default implementation of the summarize
method
on the Summary
trait. Any type implementing the Summary
trait would have
the summarize
method available on it without any further code. This is
similar to a parent class having an implementation of a method and an
inheriting child class also having the implementation of the method. We can
also override the default implementation of the summarize
method when we
implement the Summary
trait, which is similar to a child class overriding the
implementation of a method inherited from a parent class.
The other reason to use inheritance relates to the type system: to enable a child type to be used in the same places as the parent type. This is also called polymorphism, which means that you can substitute multiple objects for each other at runtime if they share certain characteristics.
Polymorphism
To many people, polymorphism is synonymous with inheritance. But it’s actually a more general concept that refers to code that can work with data of multiple types. For inheritance, those types are generally subclasses.
Rust instead uses generics to abstract over different possible types and trait bounds to impose constraints on what those types must provide. This is sometimes called bounded parametric polymorphism.
Inheritance has recently fallen out of favor as a programming design solution in many programming languages because it’s often at risk of sharing more code than necessary. Subclasses shouldn’t always share all characteristics of their parent class but will do so with inheritance. This can make a program’s design less flexible. It also introduces the possibility of calling methods on subclasses that don’t make sense or that cause errors because the methods don’t apply to the subclass. In addition, some languages will only allow single inheritance (meaning a subclass can only inherit from one class), further restricting the flexibility of a program’s design.
For these reasons, Rust takes the different approach of using trait objects instead of inheritance. Let’s look at how trait objects enable polymorphism in Rust.
Using Trait Objects That Allow for Values of Different Types
In Chapter 8, we mentioned that one limitation of vectors is that they can
store elements of only one type. We created a workaround in Listing 8-9 where
we defined a SpreadsheetCell
enum that had variants to hold integers, floats,
and text. This meant we could store different types of data in each cell and
still have a vector that represented a row of cells. This is a perfectly good
solution when our interchangeable items are a fixed set of types that we know
when our code is compiled.
However, sometimes we want our library user to be able to extend the set of
types that are valid in a particular situation. To show how we might achieve
this, we’ll create an example graphical user interface (GUI) tool that iterates
through a list of items, calling a draw
method on each one to draw it to the
screen—a common technique for GUI tools. We’ll create a library crate called
gui
that contains the structure of a GUI library. This crate might include
some types for people to use, such as Button
or TextField
. In addition,
gui
users will want to create their own types that can be drawn: for
instance, one programmer might add an Image
and another might add a
SelectBox
.
We won’t implement a fully fledged GUI library for this example but will show
how the pieces would fit together. At the time of writing the library, we can’t
know and define all the types other programmers might want to create. But we do
know that gui
needs to keep track of many values of different types, and it
needs to call a draw
method on each of these differently typed values. It
doesn’t need to know exactly what will happen when we call the draw
method,
just that the value will have that method available for us to call.
To do this in a language with inheritance, we might define a class named
Component
that has a method named draw
on it. The other classes, such as
Button
, Image
, and SelectBox
, would inherit from Component
and thus
inherit the draw
method. They could each override the draw
method to define
their custom behavior, but the framework could treat all of the types as if
they were Component
instances and call draw
on them. But because Rust
doesn’t have inheritance, we need another way to structure the gui
library to
allow users to extend it with new types.
Defining a Trait for Common Behavior
To implement the behavior we want gui
to have, we’ll define a trait named
Draw
that will have one method named draw
. Then we can define a vector that
takes a trait object. A trait object points to both an instance of a type
implementing our specified trait and a table used to look up trait methods on
that type at runtime. We create a trait object by specifying some sort of
pointer, such as a &
reference or a Box<T>
smart pointer, then the dyn
keyword, and then specifying the relevant trait. (We’ll talk about the reason
trait objects must use a pointer in Chapter 19 in the section “Dynamically
Sized Types and the Sized
Trait.”) We can
use trait objects in place of a generic or concrete type. Wherever we use a
trait object, Rust’s type system will ensure at compile time that any value
used in that context will implement the trait object’s trait. Consequently, we
don’t need to know all the possible types at compile time.
We’ve mentioned that, in Rust, we refrain from calling structs and enums
“objects” to distinguish them from other languages’ objects. In a struct or
enum, the data in the struct fields and the behavior in impl
blocks are
separated, whereas in other languages, the data and behavior combined into one
concept is often labeled an object. However, trait objects are more like
objects in other languages in the sense that they combine data and behavior.
But trait objects differ from traditional objects in that we can’t add data to
a trait object. Trait objects aren’t as generally useful as objects in other
languages: their specific purpose is to allow abstraction across common
behavior.
Listing 17-3 shows how to define a trait named Draw
with one method named
draw
:
Filename: src/lib.rs
pub trait Draw {
fn draw(&self);
}
This syntax should look familiar from our discussions on how to define traits
in Chapter 10. Next comes some new syntax: Listing 17-4 defines a struct named
Screen
that holds a vector named components
. This vector is of type
Box<dyn Draw>
, which is a trait object; it’s a stand-in for any type inside
a Box
that implements the Draw
trait.
Filename: src/lib.rs
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
On the Screen
struct, we’ll define a method named run
that will call the
draw
method on each of its components
, as shown in Listing 17-5:
Filename: src/lib.rs
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
This works differently from defining a struct that uses a generic type
parameter with trait bounds. A generic type parameter can only be substituted
with one concrete type at a time, whereas trait objects allow for multiple
concrete types to fill in for the trait object at runtime. For example, we
could have defined the Screen
struct using a generic type and a trait bound
as in Listing 17-6:
Filename: src/lib.rs
pub trait Draw {
fn draw(&self);
}
pub struct Screen<T: Draw> {
pub components: Vec<T>,
}
impl<T> Screen<T>
where
T: Draw,
{
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
This restricts us to a Screen
instance that has a list of components all of
type Button
or all of type TextField
. If you’ll only ever have homogeneous
collections, using generics and trait bounds is preferable because the
definitions will be monomorphized at compile time to use the concrete types.
On the other hand, with the method using trait objects, one Screen
instance
can hold a Vec<T>
that contains a Box<Button>
as well as a
Box<TextField>
. Let’s look at how this works, and then we’ll talk about the
runtime performance implications.
Implementing the Trait
Now we’ll add some types that implement the Draw
trait. We’ll provide the
Button
type. Again, actually implementing a GUI library is beyond the scope
of this book, so the draw
method won’t have any useful implementation in its
body. To imagine what the implementation might look like, a Button
struct
might have fields for width
, height
, and label
, as shown in Listing 17-7:
Filename: src/lib.rs
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
pub struct Button {
pub width: u32,
pub height: u32,
pub label: String,
}
impl Draw for Button {
fn draw(&self) {
// code to actually draw a button
}
}
The width
, height
, and label
fields on Button
will differ from the
fields on other components; for example, a TextField
type might have those
same fields plus a placeholder
field. Each of the types we want to draw on
the screen will implement the Draw
trait but will use different code in the
draw
method to define how to draw that particular type, as Button
has here
(without the actual GUI code, as mentioned). The Button
type, for instance,
might have an additional impl
block containing methods related to what
happens when a user clicks the button. These kinds of methods won’t apply to
types like TextField
.
If someone using our library decides to implement a SelectBox
struct that has
width
, height
, and options
fields, they implement the Draw
trait on the
SelectBox
type as well, as shown in Listing 17-8:
Filename: src/main.rs
use gui::Draw;
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
// code to actually draw a select box
}
}
fn main() {}
Our library’s user can now write their main
function to create a Screen
instance. To the Screen
instance, they can add a SelectBox
and a Button
by putting each in a Box<T>
to become a trait object. They can then call the
run
method on the Screen
instance, which will call draw
on each of the
components. Listing 17-9 shows this implementation:
Filename: src/main.rs
use gui::Draw;
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
// code to actually draw a select box
}
}
use gui::{Button, Screen};
fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from("OK"),
}),
],
};
screen.run();
}
When we wrote the library, we didn’t know that someone might add the
SelectBox
type, but our Screen
implementation was able to operate on the
new type and draw it because SelectBox
implements the Draw
trait, which
means it implements the draw
method.
This concept—of being concerned only with the messages a value responds to
rather than the value’s concrete type—is similar to the concept of duck
typing in dynamically typed languages: if it walks like a duck and quacks
like a duck, then it must be a duck! In the implementation of run
on Screen
in Listing 17-5, run
doesn’t need to know what the concrete type of each
component is. It doesn’t check whether a component is an instance of a Button
or a SelectBox
, it just calls the draw
method on the component. By
specifying Box<dyn Draw>
as the type of the values in the components
vector, we’ve defined Screen
to need values that we can call the draw
method on.
The advantage of using trait objects and Rust’s type system to write code similar to code using duck typing is that we never have to check whether a value implements a particular method at runtime or worry about getting errors if a value doesn’t implement a method but we call it anyway. Rust won’t compile our code if the values don’t implement the traits that the trait objects need.
For example, Listing 17-10 shows what happens if we try to create a Screen
with a String
as a component:
Filename: src/main.rs
use gui::Screen;
fn main() {
let screen = Screen {
components: vec![Box::new(String::from("Hi"))],
};
screen.run();
}
We’ll get this error because String
doesn’t implement the Draw
trait:
$ cargo run
Compiling gui v0.1.0 (file:///projects/gui)
error[E0277]: the trait bound `String: Draw` is not satisfied
--> src/main.rs:5:26
|
5 | components: vec![Box::new(String::from("Hi"))],
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String`
|
= help: the trait `Draw` is implemented for `Button`
= note: required for the cast from `String` to the object type `dyn Draw`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `gui` due to previous error
This error lets us know that either we’re passing something to Screen
we
didn’t mean to pass and so should pass a different type or we should implement
Draw
on String
so that Screen
is able to call draw
on it.
Trait Objects Perform Dynamic Dispatch
Recall in the “Performance of Code Using Generics” section in Chapter 10 our discussion on the monomorphization process performed by the compiler when we use trait bounds on generics: the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter. The code that results from monomorphization is doing static dispatch, which is when the compiler knows what method you’re calling at compile time. This is opposed to dynamic dispatch, which is when the compiler can’t tell at compile time which method you’re calling. In dynamic dispatch cases, the compiler emits code that at runtime will figure out which method to call.
When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. This lookup incurs a runtime cost that doesn’t occur with static dispatch. Dynamic dispatch also prevents the compiler from choosing to inline a method’s code, which in turn prevents some optimizations. However, we did get extra flexibility in the code that we wrote in Listing 17-5 and were able to support in Listing 17-9, so it’s a trade-off to consider.
Implementing an Object-Oriented Design Pattern
The state pattern is an object-oriented design pattern. The crux of the pattern is that we define a set of states a value can have internally. The states are represented by a set of state objects, and the value’s behavior changes based on its state. We’re going to work through an example of a blog post struct that has a field to hold its state, which will be a state object from the set "draft", "review", or "published".
The state objects share functionality: in Rust, of course, we use structs and traits rather than objects and inheritance. Each state object is responsible for its own behavior and for governing when it should change into another state. The value that holds a state object knows nothing about the different behavior of the states or when to transition between states.
The advantage of using the state pattern is that, when the business requirements of the program change, we won’t need to change the code of the value holding the state or the code that uses the value. We’ll only need to update the code inside one of the state objects to change its rules or perhaps add more state objects.
First, we’re going to implement the state pattern in a more traditional object-oriented way, then we’ll use an approach that’s a bit more natural in Rust. Let’s dig in to incrementally implementing a blog post workflow using the state pattern.
The final functionality will look like this:
- A blog post starts as an empty draft.
- When the draft is done, a review of the post is requested.
- When the post is approved, it gets published.
- Only published blog posts return content to print, so unapproved posts can’t accidentally be published.
Any other changes attempted on a post should have no effect. For example, if we try to approve a draft blog post before we’ve requested a review, the post should remain an unpublished draft.
Listing 17-11 shows this workflow in code form: this is an example usage of the
API we’ll implement in a library crate named blog
. This won’t compile yet
because we haven’t implemented the blog
crate.
Filename: src/main.rs
use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
We want to allow the user to create a new draft blog post with Post::new
. We
want to allow text to be added to the blog post. If we try to get the post’s
content immediately, before approval, we shouldn’t get any text because the
post is still a draft. We’ve added assert_eq!
in the code for demonstration
purposes. An excellent unit test for this would be to assert that a draft blog
post returns an empty string from the content
method, but we’re not going to
write tests for this example.
Next, we want to enable a request for a review of the post, and we want
content
to return an empty string while waiting for the review. When the post
receives approval, it should get published, meaning the text of the post will
be returned when content
is called.
Notice that the only type we’re interacting with from the crate is the Post
type. This type will use the state pattern and will hold a value that will be
one of three state objects representing the various states a post can be
in—draft, waiting for review, or published. Changing from one state to another
will be managed internally within the Post
type. The states change in
response to the methods called by our library’s users on the Post
instance,
but they don’t have to manage the state changes directly. Also, users can’t
make a mistake with the states, like publishing a post before it’s reviewed.
Defining Post
and Creating a New Instance in the Draft State
Let’s get started on the implementation of the library! We know we need a
public Post
struct that holds some content, so we’ll start with the
definition of the struct and an associated public new
function to create an
instance of Post
, as shown in Listing 17-12. We’ll also make a private
State
trait that will define the behavior that all state objects for a Post
must have.
Then Post
will hold a trait object of Box<dyn State>
inside an Option<T>
in a private field named state
to hold the state object. You’ll see why the
Option<T>
is necessary in a bit.
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
}
trait State {}
struct Draft {}
impl State for Draft {}
The State
trait defines the behavior shared by different post states. The
state objects are Draft
, PendingReview
, and Published
, and they will all
implement the State
trait. For now, the trait doesn’t have any methods, and
we’ll start by defining just the Draft
state because that is the state we
want a post to start in.
When we create a new Post
, we set its state
field to a Some
value that
holds a Box
. This Box
points to a new instance of the Draft
struct.
This ensures whenever we create a new instance of Post
, it will start out as
a draft. Because the state
field of Post
is private, there is no way to
create a Post
in any other state! In the Post::new
function, we set the
content
field to a new, empty String
.
Storing the Text of the Post Content
We saw in Listing 17-11 that we want to be able to call a method named
add_text
and pass it a &str
that is then added as the text content of the
blog post. We implement this as a method, rather than exposing the content
field as pub
, so that later we can implement a method that will control how
the content
field’s data is read. The add_text
method is pretty
straightforward, so let’s add the implementation in Listing 17-13 to the impl Post
block:
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
// --snip--
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
}
trait State {}
struct Draft {}
impl State for Draft {}
The add_text
method takes a mutable reference to self
, because we’re
changing the Post
instance that we’re calling add_text
on. We then call
push_str
on the String
in content
and pass the text
argument to add to
the saved content
. This behavior doesn’t depend on the state the post is in,
so it’s not part of the state pattern. The add_text
method doesn’t interact
with the state
field at all, but it is part of the behavior we want to
support.
Ensuring the Content of a Draft Post Is Empty
Even after we’ve called add_text
and added some content to our post, we still
want the content
method to return an empty string slice because the post is
still in the draft state, as shown on line 7 of Listing 17-11. For now, let’s
implement the content
method with the simplest thing that will fulfill this
requirement: always returning an empty string slice. We’ll change this later
once we implement the ability to change a post’s state so it can be published.
So far, posts can only be in the draft state, so the post content should always
be empty. Listing 17-14 shows this placeholder implementation:
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
// --snip--
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn content(&self) -> &str {
""
}
}
trait State {}
struct Draft {}
impl State for Draft {}
With this added content
method, everything in Listing 17-11 up to line 7
works as intended.
Requesting a Review of the Post Changes Its State
Next, we need to add functionality to request a review of a post, which should
change its state from Draft
to PendingReview
. Listing 17-15 shows this code:
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
// --snip--
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn content(&self) -> &str {
""
}
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
}
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
}
struct Draft {}
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
}
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
}
We give Post
a public method named request_review
that will take a mutable
reference to self
. Then we call an internal request_review
method on the
current state of Post
, and this second request_review
method consumes the
current state and returns a new state.
We add the request_review
method to the State
trait; all types that
implement the trait will now need to implement the request_review
method.
Note that rather than having self
, &self
, or &mut self
as the first
parameter of the method, we have self: Box<Self>
. This syntax means the
method is only valid when called on a Box
holding the type. This syntax takes
ownership of Box<Self>
, invalidating the old state so the state value of the
Post
can transform into a new state.
To consume the old state, the request_review
method needs to take ownership
of the state value. This is where the Option
in the state
field of Post
comes in: we call the take
method to take the Some
value out of the state
field and leave a None
in its place, because Rust doesn’t let us have
unpopulated fields in structs. This lets us move the state
value out of
Post
rather than borrowing it. Then we’ll set the post’s state
value to the
result of this operation.
We need to set state
to None
temporarily rather than setting it directly
with code like self.state = self.state.request_review();
to get ownership of
the state
value. This ensures Post
can’t use the old state
value after
we’ve transformed it into a new state.
The request_review
method on Draft
returns a new, boxed instance of a new
PendingReview
struct, which represents the state when a post is waiting for a
review. The PendingReview
struct also implements the request_review
method
but doesn’t do any transformations. Rather, it returns itself, because when we
request a review on a post already in the PendingReview
state, it should stay
in the PendingReview
state.
Now we can start seeing the advantages of the state pattern: the
request_review
method on Post
is the same no matter its state
value. Each
state is responsible for its own rules.
We’ll leave the content
method on Post
as is, returning an empty string
slice. We can now have a Post
in the PendingReview
state as well as in the
Draft
state, but we want the same behavior in the PendingReview
state.
Listing 17-11 now works up to line 10!
Adding approve
to Change the Behavior of content
The approve
method will be similar to the request_review
method: it will
set state
to the value that the current state says it should have when that
state is approved, as shown in Listing 17-16:
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
// --snip--
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn content(&self) -> &str {
""
}
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
}
struct Draft {}
impl State for Draft {
// --snip--
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
struct PendingReview {}
impl State for PendingReview {
// --snip--
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
Box::new(Published {})
}
}
struct Published {}
impl State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
We add the approve
method to the State
trait and add a new struct that
implements State
, the Published
state.
Similar to the way request_review
on PendingReview
works, if we call the
approve
method on a Draft
, it will have no effect because approve
will
return self
. When we call approve
on PendingReview
, it returns a new,
boxed instance of the Published
struct. The Published
struct implements the
State
trait, and for both the request_review
method and the approve
method, it returns itself, because the post should stay in the Published
state in those cases.
Now we need to update the content
method on Post
. We want the value
returned from content
to depend on the current state of the Post
, so we’re
going to have the Post
delegate to a content
method defined on its state
,
as shown in Listing 17-17:
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
// --snip--
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn content(&self) -> &str {
self.state.as_ref().unwrap().content(self)
}
// --snip--
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
}
struct Draft {}
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
Box::new(Published {})
}
}
struct Published {}
impl State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
Because the goal is to keep all these rules inside the structs that implement
State
, we call a content
method on the value in state
and pass the post
instance (that is, self
) as an argument. Then we return the value that’s
returned from using the content
method on the state
value.
We call the as_ref
method on the Option
because we want a reference to the
value inside the Option
rather than ownership of the value. Because state
is an Option<Box<dyn State>>
, when we call as_ref
, an Option<&Box<dyn State>>
is returned. If we didn’t call as_ref
, we would get an error because
we can’t move state
out of the borrowed &self
of the function parameter.
We then call the unwrap
method, which we know will never panic, because we
know the methods on Post
ensure that state
will always contain a Some
value when those methods are done. This is one of the cases we talked about in
the “Cases In Which You Have More Information Than the
Compiler” section of Chapter 9 when we
know that a None
value is never possible, even though the compiler isn’t able
to understand that.
At this point, when we call content
on the &Box<dyn State>
, deref coercion
will take effect on the &
and the Box
so the content
method will
ultimately be called on the type that implements the State
trait. That means
we need to add content
to the State
trait definition, and that is where
we’ll put the logic for what content to return depending on which state we
have, as shown in Listing 17-18:
Filename: src/lib.rs
pub struct Post {
state: Option<Box<dyn State>>,
content: String,
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn content(&self) -> &str {
self.state.as_ref().unwrap().content(self)
}
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
trait State {
// --snip--
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
fn content<'a>(&self, post: &'a Post) -> &'a str {
""
}
}
// --snip--
struct Draft {}
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
Box::new(Published {})
}
}
struct Published {}
impl State for Published {
// --snip--
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
&post.content
}
}
We add a default implementation for the content
method that returns an empty
string slice. That means we don’t need to implement content
on the Draft
and PendingReview
structs. The Published
struct will override the content
method and return the value in post.content
.
Note that we need lifetime annotations on this method, as we discussed in
Chapter 10. We’re taking a reference to a post
as an argument and returning a
reference to part of that post
, so the lifetime of the returned reference is
related to the lifetime of the post
argument.
And we’re done—all of Listing 17-11 now works! We’ve implemented the state
pattern with the rules of the blog post workflow. The logic related to the
rules lives in the state objects rather than being scattered throughout Post
.
Why Not An Enum?
You may have been wondering why we didn’t use an
enum
with the different possible post states as variants. That’s certainly a possible solution, try it and compare the end results to see which you prefer! One disadvantage of using an enum is every place that checks the value of the enum will need amatch
expression or similar to handle every possible variant. This could get more repetitive than this trait object solution.
Trade-offs of the State Pattern
We’ve shown that Rust is capable of implementing the object-oriented state
pattern to encapsulate the different kinds of behavior a post should have in
each state. The methods on Post
know nothing about the various behaviors. The
way we organized the code, we have to look in only one place to know the
different ways a published post can behave: the implementation of the State
trait on the Published
struct.
If we were to create an alternative implementation that didn’t use the state
pattern, we might instead use match
expressions in the methods on Post
or
even in the main
code that checks the state of the post and changes behavior
in those places. That would mean we would have to look in several places to
understand all the implications of a post being in the published state! This
would only increase the more states we added: each of those match
expressions
would need another arm.
With the state pattern, the Post
methods and the places we use Post
don’t
need match
expressions, and to add a new state, we would only need to add a
new struct and implement the trait methods on that one struct.
The implementation using the state pattern is easy to extend to add more functionality. To see the simplicity of maintaining code that uses the state pattern, try a few of these suggestions:
- Add a
reject
method that changes the post’s state fromPendingReview
back toDraft
. - Require two calls to
approve
before the state can be changed toPublished
. - Allow users to add text content only when a post is in the
Draft
state. Hint: have the state object responsible for what might change about the content but not responsible for modifying thePost
.
One downside of the state pattern is that, because the states implement the
transitions between states, some of the states are coupled to each other. If we
add another state between PendingReview
and Published
, such as Scheduled
,
we would have to change the code in PendingReview
to transition to
Scheduled
instead. It would be less work if PendingReview
didn’t need to
change with the addition of a new state, but that would mean switching to
another design pattern.
Another downside is that we’ve duplicated some logic. To eliminate some of the
duplication, we might try to make default implementations for the
request_review
and approve
methods on the State
trait that return self
;
however, this would violate object safety, because the trait doesn’t know what
the concrete self
will be exactly. We want to be able to use State
as a
trait object, so we need its methods to be object safe.
Other duplication includes the similar implementations of the request_review
and approve
methods on Post
. Both methods delegate to the implementation of
the same method on the value in the state
field of Option
and set the new
value of the state
field to the result. If we had a lot of methods on Post
that followed this pattern, we might consider defining a macro to eliminate the
repetition (see the “Macros” section in Chapter 19).
By implementing the state pattern exactly as it’s defined for object-oriented
languages, we’re not taking as full advantage of Rust’s strengths as we could.
Let’s look at some changes we can make to the blog
crate that can make
invalid states and transitions into compile time errors.
Encoding States and Behavior as Types
We’ll show you how to rethink the state pattern to get a different set of trade-offs. Rather than encapsulating the states and transitions completely so outside code has no knowledge of them, we’ll encode the states into different types. Consequently, Rust’s type checking system will prevent attempts to use draft posts where only published posts are allowed by issuing a compiler error.
Let’s consider the first part of main
in Listing 17-11:
Filename: src/main.rs
use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
assert_eq!("", post.content());
post.request_review();
assert_eq!("", post.content());
post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
We still enable the creation of new posts in the draft state using Post::new
and the ability to add text to the post’s content. But instead of having a
content
method on a draft post that returns an empty string, we’ll make it so
draft posts don’t have the content
method at all. That way, if we try to get
a draft post’s content, we’ll get a compiler error telling us the method
doesn’t exist. As a result, it will be impossible for us to accidentally
display draft post content in production, because that code won’t even compile.
Listing 17-19 shows the definition of a Post
struct and a DraftPost
struct,
as well as methods on each:
Filename: src/lib.rs
pub struct Post {
content: String,
}
pub struct DraftPost {
content: String,
}
impl Post {
pub fn new() -> DraftPost {
DraftPost {
content: String::new(),
}
}
pub fn content(&self) -> &str {
&self.content
}
}
impl DraftPost {
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
}
Both the Post
and DraftPost
structs have a private content
field that
stores the blog post text. The structs no longer have the state
field because
we’re moving the encoding of the state to the types of the structs. The Post
struct will represent a published post, and it has a content
method that
returns the content
.
We still have a Post::new
function, but instead of returning an instance of
Post
, it returns an instance of DraftPost
. Because content
is private
and there aren’t any functions that return Post
, it’s not possible to create
an instance of Post
right now.
The DraftPost
struct has an add_text
method, so we can add text to
content
as before, but note that DraftPost
does not have a content
method
defined! So now the program ensures all posts start as draft posts, and draft
posts don’t have their content available for display. Any attempt to get around
these constraints will result in a compiler error.
Implementing Transitions as Transformations into Different Types
So how do we get a published post? We want to enforce the rule that a draft
post has to be reviewed and approved before it can be published. A post in the
pending review state should still not display any content. Let’s implement
these constraints by adding another struct, PendingReviewPost
, defining the
request_review
method on DraftPost
to return a PendingReviewPost
, and
defining an approve
method on PendingReviewPost
to return a Post
, as
shown in Listing 17-20:
Filename: src/lib.rs
pub struct Post {
content: String,
}
pub struct DraftPost {
content: String,
}
impl Post {
pub fn new() -> DraftPost {
DraftPost {
content: String::new(),
}
}
pub fn content(&self) -> &str {
&self.content
}
}
impl DraftPost {
// --snip--
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn request_review(self) -> PendingReviewPost {
PendingReviewPost {
content: self.content,
}
}
}
pub struct PendingReviewPost {
content: String,
}
impl PendingReviewPost {
pub fn approve(self) -> Post {
Post {
content: self.content,
}
}
}
The request_review
and approve
methods take ownership of self
, thus
consuming the DraftPost
and PendingReviewPost
instances and transforming
them into a PendingReviewPost
and a published Post
, respectively. This way,
we won’t have any lingering DraftPost
instances after we’ve called
request_review
on them, and so forth. The PendingReviewPost
struct doesn’t
have a content
method defined on it, so attempting to read its content
results in a compiler error, as with DraftPost
. Because the only way to get a
published Post
instance that does have a content
method defined is to call
the approve
method on a PendingReviewPost
, and the only way to get a
PendingReviewPost
is to call the request_review
method on a DraftPost
,
we’ve now encoded the blog post workflow into the type system.
But we also have to make some small changes to main
. The request_review
and
approve
methods return new instances rather than modifying the struct they’re
called on, so we need to add more let post =
shadowing assignments to save
the returned instances. We also can’t have the assertions about the draft and
pending review posts’ contents be empty strings, nor do we need them: we can’t
compile code that tries to use the content of posts in those states any longer.
The updated code in main
is shown in Listing 17-21:
Filename: src/main.rs
use blog::Post;
fn main() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
let post = post.request_review();
let post = post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
The changes we needed to make to main
to reassign post
mean that this
implementation doesn’t quite follow the object-oriented state pattern anymore:
the transformations between the states are no longer encapsulated entirely
within the Post
implementation. However, our gain is that invalid states are
now impossible because of the type system and the type checking that happens at
compile time! This ensures that certain bugs, such as display of the content of
an unpublished post, will be discovered before they make it to production.
Try the tasks suggested at the start of this section on the blog
crate as it
is after Listing 17-21 to see what you think about the design of this version
of the code. Note that some of the tasks might be completed already in this
design.
We’ve seen that even though Rust is capable of implementing object-oriented design patterns, other patterns, such as encoding state into the type system, are also available in Rust. These patterns have different trade-offs. Although you might be very familiar with object-oriented patterns, rethinking the problem to take advantage of Rust’s features can provide benefits, such as preventing some bugs at compile time. Object-oriented patterns won’t always be the best solution in Rust due to certain features, like ownership, that object-oriented languages don’t have.
Summary
No matter whether or not you think Rust is an object-oriented language after reading this chapter, you now know that you can use trait objects to get some object-oriented features in Rust. Dynamic dispatch can give your code some flexibility in exchange for a bit of runtime performance. You can use this flexibility to implement object-oriented patterns that can help your code’s maintainability. Rust also has other features, like ownership, that object-oriented languages don’t have. An object-oriented pattern won’t always be the best way to take advantage of Rust’s strengths, but is an available option.
Next, we’ll look at patterns, which are another of Rust’s features that enable lots of flexibility. We’ve looked at them briefly throughout the book but haven’t seen their full capability yet. Let’s go!
Patterns and Matching
Patterns are a special syntax in Rust for matching against the structure of
types, both complex and simple. Using patterns in conjunction with match
expressions and other constructs gives you more control over a program’s
control flow. A pattern consists of some combination of the following:
- Literals
- Destructured arrays, enums, structs, or tuples
- Variables
- Wildcards
- Placeholders
Some example patterns include x
, (a, 3)
, and Some(Color::Red)
. In the
contexts in which patterns are valid, these components describe the shape of
data. Our program then matches values against the patterns to determine whether
it has the correct shape of data to continue running a particular piece of code.
To use a pattern, we compare it to some value. If the pattern matches the
value, we use the value parts in our code. Recall the match
expressions in
Chapter 6 that used patterns, such as the coin-sorting machine example. If the
value fits the shape of the pattern, we can use the named pieces. If it
doesn’t, the code associated with the pattern won’t run.
This chapter is a reference on all things related to patterns. We’ll cover the valid places to use patterns, the difference between refutable and irrefutable patterns, and the different kinds of pattern syntax that you might see. By the end of the chapter, you’ll know how to use patterns to express many concepts in a clear way.
All the Places Patterns Can Be Used
Patterns pop up in a number of places in Rust, and you’ve been using them a lot without realizing it! This section discusses all the places where patterns are valid.
match
Arms
As discussed in Chapter 6, we use patterns in the arms of match
expressions.
Formally, match
expressions are defined as the keyword match
, a value to
match on, and one or more match arms that consist of a pattern and an
expression to run if the value matches that arm’s pattern, like this:
match VALUE {
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
PATTERN => EXPRESSION,
}
For example, here's the match
expression from Listing 6-5 that matches on an
Option<i32>
value in the variable x
:
match x {
None => None,
Some(i) => Some(i + 1),
}
The patterns in this match
expression are the None
and Some(i)
on the
left of each arrow.
One requirement for match
expressions is that they need to be exhaustive in
the sense that all possibilities for the value in the match
expression must
be accounted for. One way to ensure you’ve covered every possibility is to have
a catchall pattern for the last arm: for example, a variable name matching any
value can never fail and thus covers every remaining case.
The particular pattern _
will match anything, but it never binds to a
variable, so it’s often used in the last match arm. The _
pattern can be
useful when you want to ignore any value not specified, for example. We’ll
cover the _
pattern in more detail in the “Ignoring Values in a
Pattern” section later in this
chapter.
Conditional if let
Expressions
In Chapter 6 we discussed how to use if let
expressions mainly as a shorter
way to write the equivalent of a match
that only matches one case.
Optionally, if let
can have a corresponding else
containing code to run if
the pattern in the if let
doesn’t match.
Listing 18-1 shows that it’s also possible to mix and match if let
, else if
, and else if let
expressions. Doing so gives us more flexibility than a
match
expression in which we can express only one value to compare with the
patterns. Also, Rust doesn't require that the conditions in a series of if let
, else if
, else if let
arms relate to each other.
The code in Listing 18-1 determines what color to make your background based on a series of checks for several conditions. For this example, we’ve created variables with hardcoded values that a real program might receive from user input.
Filename: src/main.rs
fn main() { let favorite_color: Option<&str> = None; let is_tuesday = false; let age: Result<u8, _> = "34".parse(); if let Some(color) = favorite_color { println!("Using your favorite color, {color}, as the background"); } else if is_tuesday { println!("Tuesday is green day!"); } else if let Ok(age) = age { if age > 30 { println!("Using purple as the background color"); } else { println!("Using orange as the background color"); } } else { println!("Using blue as the background color"); } }
If the user specifies a favorite color, that color is used as the background. If no favorite color is specified and today is Tuesday, the background color is green. Otherwise, if the user specifies their age as a string and we can parse it as a number successfully, the color is either purple or orange depending on the value of the number. If none of these conditions apply, the background color is blue.
This conditional structure lets us support complex requirements. With the
hardcoded values we have here, this example will print Using purple as the background color
.
You can see that if let
can also introduce shadowed variables in the same way
that match
arms can: the line if let Ok(age) = age
introduces a new
shadowed age
variable that contains the value inside the Ok
variant. This
means we need to place the if age > 30
condition within that block: we can’t
combine these two conditions into if let Ok(age) = age && age > 30
. The
shadowed age
we want to compare to 30 isn’t valid until the new scope starts
with the curly bracket.
The downside of using if let
expressions is that the compiler doesn’t check
for exhaustiveness, whereas with match
expressions it does. If we omitted the
last else
block and therefore missed handling some cases, the compiler would
not alert us to the possible logic bug.
while let
Conditional Loops
Similar in construction to if let
, the while let
conditional loop allows a
while
loop to run for as long as a pattern continues to match. In Listing
18-2 we code a while let
loop that uses a vector as a stack and prints the
values in the vector in the opposite order in which they were pushed.
fn main() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("{}", top); } }
This example prints 3, 2, and then 1. The pop
method takes the last element
out of the vector and returns Some(value)
. If the vector is empty, pop
returns None
. The while
loop continues running the code in its block as
long as pop
returns Some
. When pop
returns None
, the loop stops. We can
use while let
to pop every element off our stack.
for
Loops
In a for
loop, the value that directly follows the keyword for
is a
pattern. For example, in for x in y
the x
is the pattern. Listing 18-3
demonstrates how to use a pattern in a for
loop to destructure, or break
apart, a tuple as part of the for
loop.
fn main() { let v = vec!['a', 'b', 'c']; for (index, value) in v.iter().enumerate() { println!("{} is at index {}", value, index); } }
The code in Listing 18-3 will print the following:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
Finished dev [unoptimized + debuginfo] target(s) in 0.52s
Running `target/debug/patterns`
a is at index 0
b is at index 1
c is at index 2
We adapt an iterator using the enumerate
method so it produces a value and
the index for that value, placed into a tuple. The first value produced is the
tuple (0, 'a')
. When this value is matched to the pattern (index, value)
,
index
will be 0
and value
will be 'a'
, printing the first line of the
output.
let
Statements
Prior to this chapter, we had only explicitly discussed using patterns with
match
and if let
, but in fact, we’ve used patterns in other places as well,
including in let
statements. For example, consider this straightforward
variable assignment with let
:
#![allow(unused)] fn main() { let x = 5; }
Every time you've used a let
statement like this you've been using patterns,
although you might not have realized it! More formally, a let
statement looks
like this:
let PATTERN = EXPRESSION;
In statements like let x = 5;
with a variable name in the PATTERN
slot, the
variable name is just a particularly simple form of a pattern. Rust compares
the expression against the pattern and assigns any names it finds. So in the
let x = 5;
example, x
is a pattern that means “bind what matches here to
the variable x
.” Because the name x
is the whole pattern, this pattern
effectively means “bind everything to the variable x
, whatever the value is.”
To see the pattern matching aspect of let
more clearly, consider Listing
18-4, which uses a pattern with let
to destructure a tuple.
fn main() { let (x, y, z) = (1, 2, 3); }
Here, we match a tuple against a pattern. Rust compares the value (1, 2, 3)
to the pattern (x, y, z)
and sees that the value matches the pattern, so Rust
binds 1
to x
, 2
to y
, and 3
to z
. You can think of this tuple
pattern as nesting three individual variable patterns inside it.
If the number of elements in the pattern doesn’t match the number of elements in the tuple, the overall type won’t match and we’ll get a compiler error. For example, Listing 18-5 shows an attempt to destructure a tuple with three elements into two variables, which won’t work.
fn main() {
let (x, y) = (1, 2, 3);
}
Attempting to compile this code results in this type error:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0308]: mismatched types
--> src/main.rs:2:9
|
2 | let (x, y) = (1, 2, 3);
| ^^^^^^ --------- this expression has type `({integer}, {integer}, {integer})`
| |
| expected a tuple with 3 elements, found one with 2 elements
|
= note: expected tuple `({integer}, {integer}, {integer})`
found tuple `(_, _)`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `patterns` due to previous error
To fix the error, we could ignore one or more of the values in the tuple using
_
or ..
, as you’ll see in the “Ignoring Values in a
Pattern” section. If the problem
is that we have too many variables in the pattern, the solution is to make the
types match by removing variables so the number of variables equals the number
of elements in the tuple.
Function Parameters
Function parameters can also be patterns. The code in Listing 18-6, which
declares a function named foo
that takes one parameter named x
of type
i32
, should by now look familiar.
fn foo(x: i32) { // code goes here } fn main() {}
The x
part is a pattern! As we did with let
, we could match a tuple in a
function’s arguments to the pattern. Listing 18-7 splits the values in a tuple
as we pass it to a function.
Filename: src/main.rs
fn print_coordinates(&(x, y): &(i32, i32)) { println!("Current location: ({}, {})", x, y); } fn main() { let point = (3, 5); print_coordinates(&point); }
This code prints Current location: (3, 5)
. The values &(3, 5)
match the
pattern &(x, y)
, so x
is the value 3
and y
is the value 5
.
We can also use patterns in closure parameter lists in the same way as in function parameter lists, because closures are similar to functions, as discussed in Chapter 13.
At this point, you’ve seen several ways of using patterns, but patterns don’t work the same in every place we can use them. In some places, the patterns must be irrefutable; in other circumstances, they can be refutable. We’ll discuss these two concepts next.
Refutability: Whether a Pattern Might Fail to Match
Patterns come in two forms: refutable and irrefutable. Patterns that will match
for any possible value passed are irrefutable. An example would be x
in the
statement let x = 5;
because x
matches anything and therefore cannot fail
to match. Patterns that can fail to match for some possible value are
refutable. An example would be Some(x)
in the expression if let Some(x) = a_value
because if the value in the a_value
variable is None
rather than
Some
, the Some(x)
pattern will not match.
Function parameters, let
statements, and for
loops can only accept
irrefutable patterns, because the program cannot do anything meaningful when
values don’t match. The if let
and while let
expressions accept
refutable and irrefutable patterns, but the compiler warns against
irrefutable patterns because by definition they’re intended to handle possible
failure: the functionality of a conditional is in its ability to perform
differently depending on success or failure.
In general, you shouldn’t have to worry about the distinction between refutable and irrefutable patterns; however, you do need to be familiar with the concept of refutability so you can respond when you see it in an error message. In those cases, you’ll need to change either the pattern or the construct you’re using the pattern with, depending on the intended behavior of the code.
Let’s look at an example of what happens when we try to use a refutable pattern
where Rust requires an irrefutable pattern and vice versa. Listing 18-8 shows a
let
statement, but for the pattern we’ve specified Some(x)
, a refutable
pattern. As you might expect, this code will not compile.
fn main() {
let some_option_value: Option<i32> = None;
let Some(x) = some_option_value;
}
If some_option_value
was a None
value, it would fail to match the pattern
Some(x)
, meaning the pattern is refutable. However, the let
statement can
only accept an irrefutable pattern because there is nothing valid the code can
do with a None
value. At compile time, Rust will complain that we’ve tried to
use a refutable pattern where an irrefutable pattern is required:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error[E0005]: refutable pattern in local binding: `None` not covered
--> src/main.rs:3:9
|
3 | let Some(x) = some_option_value;
| ^^^^^^^ pattern `None` not covered
|
= note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
= note: for more information, visit https://doc.rust-lang.org/book/ch18-02-refutability.html
note: `Option<i32>` defined here
--> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:518:1
|
= note:
/rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/core/src/option.rs:522:5: not covered
= note: the matched value is of type `Option<i32>`
help: you might want to use `if let` to ignore the variant that isn't matched
|
3 | let x = if let Some(x) = some_option_value { x } else { todo!() };
| ++++++++++ ++++++++++++++++++++++
help: alternatively, you might want to use let else to handle the variant that isn't matched
|
3 | let Some(x) = some_option_value else { todo!() };
| ++++++++++++++++
For more information about this error, try `rustc --explain E0005`.
error: could not compile `patterns` due to previous error
Because we didn’t cover (and couldn’t cover!) every valid value with the
pattern Some(x)
, Rust rightfully produces a compiler error.
If we have a refutable pattern where an irrefutable pattern is needed, we can
fix it by changing the code that uses the pattern: instead of using let
, we
can use if let
. Then if the pattern doesn’t match, the code will just skip
the code in the curly brackets, giving it a way to continue validly. Listing
18-9 shows how to fix the code in Listing 18-8.
fn main() { let some_option_value: Option<i32> = None; if let Some(x) = some_option_value { println!("{}", x); } }
We’ve given the code an out! This code is perfectly valid, although it means we
cannot use an irrefutable pattern without receiving an error. If we give if let
a pattern that will always match, such as x
, as shown in Listing 18-10,
the compiler will give a warning.
fn main() { if let x = 5 { println!("{}", x); }; }
Rust complains that it doesn’t make sense to use if let
with an irrefutable
pattern:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
warning: irrefutable `if let` pattern
--> src/main.rs:2:8
|
2 | if let x = 5 {
| ^^^^^^^^^
|
= note: this pattern will always match, so the `if let` is useless
= help: consider replacing the `if let` with a `let`
= note: `#[warn(irrefutable_let_patterns)]` on by default
warning: `patterns` (bin "patterns") generated 1 warning
Finished dev [unoptimized + debuginfo] target(s) in 0.39s
Running `target/debug/patterns`
5
For this reason, match arms must use refutable patterns, except for the last
arm, which should match any remaining values with an irrefutable pattern. Rust
allows us to use an irrefutable pattern in a match
with only one arm, but
this syntax isn’t particularly useful and could be replaced with a simpler
let
statement.
Now that you know where to use patterns and the difference between refutable and irrefutable patterns, let’s cover all the syntax we can use to create patterns.
Pattern Syntax
In this section, we gather all the syntax valid in patterns and discuss why and when you might want to use each one.
Matching Literals
As you saw in Chapter 6, you can match patterns against literals directly. The following code gives some examples:
fn main() { let x = 1; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), _ => println!("anything"), } }
This code prints one
because the value in x
is 1. This syntax is useful
when you want your code to take an action if it gets a particular concrete
value.
Matching Named Variables
Named variables are irrefutable patterns that match any value, and we’ve used
them many times in the book. However, there is a complication when you use
named variables in match
expressions. Because match
starts a new scope,
variables declared as part of a pattern inside the match
expression will
shadow those with the same name outside the match
construct, as is the case
with all variables. In Listing 18-11, we declare a variable named x
with the
value Some(5)
and a variable y
with the value 10
. We then create a
match
expression on the value x
. Look at the patterns in the match arms and
println!
at the end, and try to figure out what the code will print before
running this code or reading further.
Filename: src/main.rs
fn main() { let x = Some(5); let y = 10; match x { Some(50) => println!("Got 50"), Some(y) => println!("Matched, y = {y}"), _ => println!("Default case, x = {:?}", x), } println!("at the end: x = {:?}, y = {y}", x); }
Let’s walk through what happens when the match
expression runs. The pattern
in the first match arm doesn’t match the defined value of x
, so the code
continues.
The pattern in the second match arm introduces a new variable named y
that
will match any value inside a Some
value. Because we’re in a new scope inside
the match
expression, this is a new y
variable, not the y
we declared at
the beginning with the value 10. This new y
binding will match any value
inside a Some
, which is what we have in x
. Therefore, this new y
binds to
the inner value of the Some
in x
. That value is 5
, so the expression for
that arm executes and prints Matched, y = 5
.
If x
had been a None
value instead of Some(5)
, the patterns in the first
two arms wouldn’t have matched, so the value would have matched to the
underscore. We didn’t introduce the x
variable in the pattern of the
underscore arm, so the x
in the expression is still the outer x
that hasn’t
been shadowed. In this hypothetical case, the match
would print Default case, x = None
.
When the match
expression is done, its scope ends, and so does the scope of
the inner y
. The last println!
produces at the end: x = Some(5), y = 10
.
To create a match
expression that compares the values of the outer x
and
y
, rather than introducing a shadowed variable, we would need to use a match
guard conditional instead. We’ll talk about match guards later in the “Extra
Conditionals with Match Guards” section.
Multiple Patterns
In match
expressions, you can match multiple patterns using the |
syntax,
which is the pattern or operator. For example, in the following code we match
the value of x
against the match arms, the first of which has an or option,
meaning if the value of x
matches either of the values in that arm, that
arm’s code will run:
fn main() { let x = 1; match x { 1 | 2 => println!("one or two"), 3 => println!("three"), _ => println!("anything"), } }
This code prints one or two
.
Matching Ranges of Values with ..=
The ..=
syntax allows us to match to an inclusive range of values. In the
following code, when a pattern matches any of the values within the given
range, that arm will execute:
fn main() { let x = 5; match x { 1..=5 => println!("one through five"), _ => println!("something else"), } }
If x
is 1, 2, 3, 4, or 5, the first arm will match. This syntax is more
convenient for multiple match values than using the |
operator to express the
same idea; if we were to use |
we would have to specify 1 | 2 | 3 | 4 | 5
.
Specifying a range is much shorter, especially if we want to match, say, any
number between 1 and 1,000!
The compiler checks that the range isn’t empty at compile time, and because the
only types for which Rust can tell if a range is empty or not are char
and
numeric values, ranges are only allowed with numeric or char
values.
Here is an example using ranges of char
values:
fn main() { let x = 'c'; match x { 'a'..='j' => println!("early ASCII letter"), 'k'..='z' => println!("late ASCII letter"), _ => println!("something else"), } }
Rust can tell that 'c'
is within the first pattern’s range and prints early ASCII letter
.
Destructuring to Break Apart Values
We can also use patterns to destructure structs, enums, and tuples to use different parts of these values. Let’s walk through each value.
Destructuring Structs
Listing 18-12 shows a Point
struct with two fields, x
and y
, that we can
break apart using a pattern with a let
statement.
Filename: src/main.rs
struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 7 }; let Point { x: a, y: b } = p; assert_eq!(0, a); assert_eq!(7, b); }
This code creates the variables a
and b
that match the values of the x
and y
fields of the p
struct. This example shows that the names of the
variables in the pattern don’t have to match the field names of the struct.
However, it’s common to match the variable names to the field names to make it
easier to remember which variables came from which fields. Because of this
common usage, and because writing let Point { x: x, y: y } = p;
contains a
lot of duplication, Rust has a shorthand for patterns that match struct fields:
you only need to list the name of the struct field, and the variables created
from the pattern will have the same names. Listing 18-13 behaves in the same
way as the code in Listing 18-12, but the variables created in the let
pattern are x
and y
instead of a
and b
.
Filename: src/main.rs
struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 7 }; let Point { x, y } = p; assert_eq!(0, x); assert_eq!(7, y); }
This code creates the variables x
and y
that match the x
and y
fields
of the p
variable. The outcome is that the variables x
and y
contain the
values from the p
struct.
We can also destructure with literal values as part of the struct pattern rather than creating variables for all the fields. Doing so allows us to test some of the fields for particular values while creating variables to destructure the other fields.
In Listing 18-14, we have a match
expression that separates Point
values
into three cases: points that lie directly on the x
axis (which is true when
y = 0
), on the y
axis (x = 0
), or neither.
Filename: src/main.rs
struct Point { x: i32, y: i32, } fn main() { let p = Point { x: 0, y: 7 }; match p { Point { x, y: 0 } => println!("On the x axis at {x}"), Point { x: 0, y } => println!("On the y axis at {y}"), Point { x, y } => { println!("On neither axis: ({x}, {y})"); } } }
The first arm will match any point that lies on the x
axis by specifying that
the y
field matches if its value matches the literal 0
. The pattern still
creates an x
variable that we can use in the code for this arm.
Similarly, the second arm matches any point on the y
axis by specifying that
the x
field matches if its value is 0
and creates a variable y
for the
value of the y
field. The third arm doesn’t specify any literals, so it
matches any other Point
and creates variables for both the x
and y
fields.
In this example, the value p
matches the second arm by virtue of x
containing a 0, so this code will print On the y axis at 7
.
Remember that a match
expression stops checking arms once it has found the
first matching pattern, so even though Point { x: 0, y: 0}
is on the x
axis
and the y
axis, this code would only print On the x axis at 0
.
Destructuring Enums
We've destructured enums in this book (for example, Listing 6-5 in Chapter 6),
but haven’t yet explicitly discussed that the pattern to destructure an enum
corresponds to the way the data stored within the enum is defined. As an
example, in Listing 18-15 we use the Message
enum from Listing 6-2 and write
a match
with patterns that will destructure each inner value.
Filename: src/main.rs
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), } fn main() { let msg = Message::ChangeColor(0, 160, 255); match msg { Message::Quit => { println!("The Quit variant has no data to destructure."); } Message::Move { x, y } => { println!("Move in the x direction {x} and in the y direction {y}"); } Message::Write(text) => { println!("Text message: {text}"); } Message::ChangeColor(r, g, b) => { println!("Change the color to red {r}, green {g}, and blue {b}",) } } }
This code will print Change the color to red 0, green 160, and blue 255
. Try
changing the value of msg
to see the code from the other arms run.
For enum variants without any data, like Message::Quit
, we can’t destructure
the value any further. We can only match on the literal Message::Quit
value,
and no variables are in that pattern.
For struct-like enum variants, such as Message::Move
, we can use a pattern
similar to the pattern we specify to match structs. After the variant name, we
place curly brackets and then list the fields with variables so we break apart
the pieces to use in the code for this arm. Here we use the shorthand form as
we did in Listing 18-13.
For tuple-like enum variants, like Message::Write
that holds a tuple with one
element and Message::ChangeColor
that holds a tuple with three elements, the
pattern is similar to the pattern we specify to match tuples. The number of
variables in the pattern must match the number of elements in the variant we’re
matching.
Destructuring Nested Structs and Enums
So far, our examples have all been matching structs or enums one level deep,
but matching can work on nested items too! For example, we can refactor the
code in Listing 18-15 to support RGB and HSV colors in the ChangeColor
message, as shown in Listing 18-16.
enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } fn main() { let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); match msg { Message::ChangeColor(Color::Rgb(r, g, b)) => { println!("Change color to red {r}, green {g}, and blue {b}"); } Message::ChangeColor(Color::Hsv(h, s, v)) => { println!("Change color to hue {h}, saturation {s}, value {v}") } _ => (), } }
The pattern of the first arm in the match
expression matches a
Message::ChangeColor
enum variant that contains a Color::Rgb
variant; then
the pattern binds to the three inner i32
values. The pattern of the second
arm also matches a Message::ChangeColor
enum variant, but the inner enum
matches Color::Hsv
instead. We can specify these complex conditions in one
match
expression, even though two enums are involved.
Destructuring Structs and Tuples
We can mix, match, and nest destructuring patterns in even more complex ways. The following example shows a complicated destructure where we nest structs and tuples inside a tuple and destructure all the primitive values out:
fn main() { struct Point { x: i32, y: i32, } let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); }
This code lets us break complex types into their component parts so we can use the values we’re interested in separately.
Destructuring with patterns is a convenient way to use pieces of values, such as the value from each field in a struct, separately from each other.
Ignoring Values in a Pattern
You’ve seen that it’s sometimes useful to ignore values in a pattern, such as
in the last arm of a match
, to get a catchall that doesn’t actually do
anything but does account for all remaining possible values. There are a few
ways to ignore entire values or parts of values in a pattern: using the _
pattern (which you’ve seen), using the _
pattern within another pattern,
using a name that starts with an underscore, or using ..
to ignore remaining
parts of a value. Let’s explore how and why to use each of these patterns.
Ignoring an Entire Value with _
We’ve used the underscore as a wildcard pattern that will match any value but
not bind to the value. This is especially useful as the last arm in a match
expression, but we can also use it in any pattern, including function
parameters, as shown in Listing 18-17.
Filename: src/main.rs
fn foo(_: i32, y: i32) { println!("This code only uses the y parameter: {}", y); } fn main() { foo(3, 4); }
This code will completely ignore the value 3
passed as the first argument,
and will print This code only uses the y parameter: 4
.
In most cases when you no longer need a particular function parameter, you would change the signature so it doesn’t include the unused parameter. Ignoring a function parameter can be especially useful in cases when, for example, you're implementing a trait when you need a certain type signature but the function body in your implementation doesn’t need one of the parameters. You then avoid getting a compiler warning about unused function parameters, as you would if you used a name instead.
Ignoring Parts of a Value with a Nested _
We can also use _
inside another pattern to ignore just part of a value, for
example, when we want to test for only part of a value but have no use for the
other parts in the corresponding code we want to run. Listing 18-18 shows code
responsible for managing a setting’s value. The business requirements are that
the user should not be allowed to overwrite an existing customization of a
setting but can unset the setting and give it a value if it is currently unset.
fn main() { let mut setting_value = Some(5); let new_setting_value = Some(10); match (setting_value, new_setting_value) { (Some(_), Some(_)) => { println!("Can't overwrite an existing customized value"); } _ => { setting_value = new_setting_value; } } println!("setting is {:?}", setting_value); }
This code will print Can't overwrite an existing customized value
and then
setting is Some(5)
. In the first match arm, we don’t need to match on or use
the values inside either Some
variant, but we do need to test for the case
when setting_value
and new_setting_value
are the Some
variant. In that
case, we print the reason for not changing setting_value
, and it doesn’t get
changed.
In all other cases (if either setting_value
or new_setting_value
are
None
) expressed by the _
pattern in the second arm, we want to allow
new_setting_value
to become setting_value
.
We can also use underscores in multiple places within one pattern to ignore particular values. Listing 18-19 shows an example of ignoring the second and fourth values in a tuple of five items.
fn main() { let numbers = (2, 4, 8, 16, 32); match numbers { (first, _, third, _, fifth) => { println!("Some numbers: {first}, {third}, {fifth}") } } }
This code will print Some numbers: 2, 8, 32
, and the values 4 and 16 will be
ignored.
Ignoring an Unused Variable by Starting Its Name with _
If you create a variable but don’t use it anywhere, Rust will usually issue a warning because an unused variable could be a bug. However, sometimes it’s useful to be able to create a variable you won’t use yet, such as when you’re prototyping or just starting a project. In this situation, you can tell Rust not to warn you about the unused variable by starting the name of the variable with an underscore. In Listing 18-20, we create two unused variables, but when we compile this code, we should only get a warning about one of them.
Filename: src/main.rs
fn main() { let _x = 5; let y = 10; }
Here we get a warning about not using the variable y
, but we don’t get a
warning about not using _x
.
Note that there is a subtle difference between using only _
and using a name
that starts with an underscore. The syntax _x
still binds the value to the
variable, whereas _
doesn’t bind at all. To show a case where this
distinction matters, Listing 18-21 will provide us with an error.
fn main() {
let s = Some(String::from("Hello!"));
if let Some(_s) = s {
println!("found a string");
}
println!("{:?}", s);
}
We’ll receive an error because the s
value will still be moved into _s
,
which prevents us from using s
again. However, using the underscore by itself
doesn’t ever bind to the value. Listing 18-22 will compile without any errors
because s
doesn’t get moved into _
.
fn main() { let s = Some(String::from("Hello!")); if let Some(_) = s { println!("found a string"); } println!("{:?}", s); }
This code works just fine because we never bind s
to anything; it isn’t moved.
Ignoring Remaining Parts of a Value with ..
With values that have many parts, we can use the ..
syntax to use specific
parts and ignore the rest, avoiding the need to list underscores for each
ignored value. The ..
pattern ignores any parts of a value that we haven’t
explicitly matched in the rest of the pattern. In Listing 18-23, we have a
Point
struct that holds a coordinate in three-dimensional space. In the
match
expression, we want to operate only on the x
coordinate and ignore
the values in the y
and z
fields.
fn main() { struct Point { x: i32, y: i32, z: i32, } let origin = Point { x: 0, y: 0, z: 0 }; match origin { Point { x, .. } => println!("x is {}", x), } }
We list the x
value and then just include the ..
pattern. This is quicker
than having to list y: _
and z: _
, particularly when we’re working with
structs that have lots of fields in situations where only one or two fields are
relevant.
The syntax ..
will expand to as many values as it needs to be. Listing 18-24
shows how to use ..
with a tuple.
Filename: src/main.rs
fn main() { let numbers = (2, 4, 8, 16, 32); match numbers { (first, .., last) => { println!("Some numbers: {first}, {last}"); } } }
In this code, the first and last value are matched with first
and last
. The
..
will match and ignore everything in the middle.
However, using ..
must be unambiguous. If it is unclear which values are
intended for matching and which should be ignored, Rust will give us an error.
Listing 18-25 shows an example of using ..
ambiguously, so it will not
compile.
Filename: src/main.rs
fn main() {
let numbers = (2, 4, 8, 16, 32);
match numbers {
(.., second, ..) => {
println!("Some numbers: {}", second)
},
}
}
When we compile this example, we get this error:
$ cargo run
Compiling patterns v0.1.0 (file:///projects/patterns)
error: `..` can only be used once per tuple pattern
--> src/main.rs:5:22
|
5 | (.., second, ..) => {
| -- ^^ can only be used once per tuple pattern
| |
| previously used here
error: could not compile `patterns` due to previous error
It’s impossible for Rust to determine how many values in the tuple to ignore
before matching a value with second
and then how many further values to
ignore thereafter. This code could mean that we want to ignore 2
, bind
second
to 4
, and then ignore 8
, 16
, and 32
; or that we want to ignore
2
and 4
, bind second
to 8
, and then ignore 16
and 32
; and so forth.
The variable name second
doesn’t mean anything special to Rust, so we get a
compiler error because using ..
in two places like this is ambiguous.
Extra Conditionals with Match Guards
A match guard is an additional if
condition, specified after the pattern in
a match
arm, that must also match for that arm to be chosen. Match guards are
useful for expressing more complex ideas than a pattern alone allows.
The condition can use variables created in the pattern. Listing 18-26 shows a
match
where the first arm has the pattern Some(x)
and also has a match
guard of if x % 2 == 0
(which will be true if the number is even).
fn main() { let num = Some(4); match num { Some(x) if x % 2 == 0 => println!("The number {} is even", x), Some(x) => println!("The number {} is odd", x), None => (), } }
This example will print The number 4 is even
. When num
is compared to the
pattern in the first arm, it matches, because Some(4)
matches Some(x)
. Then
the match guard checks whether the remainder of dividing x
by 2 is equal to
0, and because it is, the first arm is selected.
If num
had been Some(5)
instead, the match guard in the first arm would
have been false because the remainder of 5 divided by 2 is 1, which is not
equal to 0. Rust would then go to the second arm, which would match because the
second arm doesn’t have a match guard and therefore matches any Some
variant.
There is no way to express the if x % 2 == 0
condition within a pattern, so
the match guard gives us the ability to express this logic. The downside of
this additional expressiveness is that the compiler doesn't try to check for
exhaustiveness when match guard expressions are involved.
In Listing 18-11, we mentioned that we could use match guards to solve our
pattern-shadowing problem. Recall that we created a new variable inside the
pattern in the match
expression instead of using the variable outside the
match
. That new variable meant we couldn’t test against the value of the
outer variable. Listing 18-27 shows how we can use a match guard to fix this
problem.
Filename: src/main.rs
fn main() { let x = Some(5); let y = 10; match x { Some(50) => println!("Got 50"), Some(n) if n == y => println!("Matched, n = {n}"), _ => println!("Default case, x = {:?}", x), } println!("at the end: x = {:?}, y = {y}", x); }
This code will now print Default case, x = Some(5)
. The pattern in the second
match arm doesn’t introduce a new variable y
that would shadow the outer y
,
meaning we can use the outer y
in the match guard. Instead of specifying the
pattern as Some(y)
, which would have shadowed the outer y
, we specify
Some(n)
. This creates a new variable n
that doesn’t shadow anything because
there is no n
variable outside the match
.
The match guard if n == y
is not a pattern and therefore doesn’t introduce
new variables. This y
is the outer y
rather than a new shadowed y
, and
we can look for a value that has the same value as the outer y
by comparing
n
to y
.
You can also use the or operator |
in a match guard to specify multiple
patterns; the match guard condition will apply to all the patterns. Listing
18-28 shows the precedence when combining a pattern that uses |
with a match
guard. The important part of this example is that the if y
match guard
applies to 4
, 5
, and 6
, even though it might look like if y
only
applies to 6
.
fn main() { let x = 4; let y = false; match x { 4 | 5 | 6 if y => println!("yes"), _ => println!("no"), } }
The match condition states that the arm only matches if the value of x
is
equal to 4
, 5
, or 6
and if y
is true
. When this code runs, the
pattern of the first arm matches because x
is 4
, but the match guard if y
is false, so the first arm is not chosen. The code moves on to the second arm,
which does match, and this program prints no
. The reason is that the if
condition applies to the whole pattern 4 | 5 | 6
, not only to the last value
6
. In other words, the precedence of a match guard in relation to a pattern
behaves like this:
(4 | 5 | 6) if y => ...
rather than this:
4 | 5 | (6 if y) => ...
After running the code, the precedence behavior is evident: if the match guard
were applied only to the final value in the list of values specified using the
|
operator, the arm would have matched and the program would have printed
yes
.
@
Bindings
The at operator @
lets us create a variable that holds a value at the same
time as we’re testing that value for a pattern match. In Listing 18-29, we want
to test that a Message::Hello
id
field is within the range 3..=7
. We also
want to bind the value to the variable id_variable
so we can use it in the
code associated with the arm. We could name this variable id
, the same as the
field, but for this example we’ll use a different name.
fn main() { enum Message { Hello { id: i32 }, } let msg = Message::Hello { id: 5 }; match msg { Message::Hello { id: id_variable @ 3..=7, } => println!("Found an id in range: {}", id_variable), Message::Hello { id: 10..=12 } => { println!("Found an id in another range") } Message::Hello { id } => println!("Found some other id: {}", id), } }
This example will print Found an id in range: 5
. By specifying id_variable @
before the range 3..=7
, we’re capturing whatever value matched the range
while also testing that the value matched the range pattern.
In the second arm, where we only have a range specified in the pattern, the code
associated with the arm doesn’t have a variable that contains the actual value
of the id
field. The id
field’s value could have been 10, 11, or 12, but
the code that goes with that pattern doesn’t know which it is. The pattern code
isn’t able to use the value from the id
field, because we haven’t saved the
id
value in a variable.
In the last arm, where we’ve specified a variable without a range, we do have
the value available to use in the arm’s code in a variable named id
. The
reason is that we’ve used the struct field shorthand syntax. But we haven’t
applied any test to the value in the id
field in this arm, as we did with the
first two arms: any value would match this pattern.
Using @
lets us test a value and save it in a variable within one pattern.
Summary
Rust’s patterns are very useful in distinguishing between different kinds of
data. When used in match
expressions, Rust ensures your patterns cover every
possible value, or your program won’t compile. Patterns in let
statements and
function parameters make those constructs more useful, enabling the
destructuring of values into smaller parts at the same time as assigning to
variables. We can create simple or complex patterns to suit our needs.
Next, for the penultimate chapter of the book, we’ll look at some advanced aspects of a variety of Rust’s features.
Advanced Features
By now, you’ve learned the most commonly used parts of the Rust programming language. Before we do one more project in Chapter 20, we’ll look at a few aspects of the language you might run into every once in a while, but may not use every day. You can use this chapter as a reference for when you encounter any unknowns. The features covered here are useful in very specific situations. Although you might not reach for them often, we want to make sure you have a grasp of all the features Rust has to offer.
In this chapter, we’ll cover:
- Unsafe Rust: how to opt out of some of Rust’s guarantees and take responsibility for manually upholding those guarantees
- Advanced traits: associated types, default type parameters, fully qualified syntax, supertraits, and the newtype pattern in relation to traits
- Advanced types: more about the newtype pattern, type aliases, the never type, and dynamically sized types
- Advanced functions and closures: function pointers and returning closures
- Macros: ways to define code that defines more code at compile time
It’s a panoply of Rust features with something for everyone! Let’s dive in!
Unsafe Rust
All the code we’ve discussed so far has had Rust’s memory safety guarantees enforced at compile time. However, Rust has a second language hidden inside it that doesn’t enforce these memory safety guarantees: it’s called unsafe Rust and works just like regular Rust, but gives us extra superpowers.
Unsafe Rust exists because, by nature, static analysis is conservative. When the compiler tries to determine whether or not code upholds the guarantees, it’s better for it to reject some valid programs than to accept some invalid programs. Although the code might be okay, if the Rust compiler doesn’t have enough information to be confident, it will reject the code. In these cases, you can use unsafe code to tell the compiler, “Trust me, I know what I’m doing.” Be warned, however, that you use unsafe Rust at your own risk: if you use unsafe code incorrectly, problems can occur due to memory unsafety, such as null pointer dereferencing.
Another reason Rust has an unsafe alter ego is that the underlying computer hardware is inherently unsafe. If Rust didn’t let you do unsafe operations, you couldn’t do certain tasks. Rust needs to allow you to do low-level systems programming, such as directly interacting with the operating system or even writing your own operating system. Working with low-level systems programming is one of the goals of the language. Let’s explore what we can do with unsafe Rust and how to do it.
Unsafe Superpowers
To switch to unsafe Rust, use the unsafe
keyword and then start a new block
that holds the unsafe code. You can take five actions in unsafe Rust that you
can’t in safe Rust, which we call unsafe superpowers. Those superpowers
include the ability to:
- Dereference a raw pointer
- Call an unsafe function or method
- Access or modify a mutable static variable
- Implement an unsafe trait
- Access fields of
union
s
It’s important to understand that unsafe
doesn’t turn off the borrow checker
or disable any other of Rust’s safety checks: if you use a reference in unsafe
code, it will still be checked. The unsafe
keyword only gives you access to
these five features that are then not checked by the compiler for memory
safety. You’ll still get some degree of safety inside of an unsafe block.
In addition, unsafe
does not mean the code inside the block is necessarily
dangerous or that it will definitely have memory safety problems: the intent is
that as the programmer, you’ll ensure the code inside an unsafe
block will
access memory in a valid way.
People are fallible, and mistakes will happen, but by requiring these five
unsafe operations to be inside blocks annotated with unsafe
you’ll know that
any errors related to memory safety must be within an unsafe
block. Keep
unsafe
blocks small; you’ll be thankful later when you investigate memory
bugs.
To isolate unsafe code as much as possible, it’s best to enclose unsafe code
within a safe abstraction and provide a safe API, which we’ll discuss later in
the chapter when we examine unsafe functions and methods. Parts of the standard
library are implemented as safe abstractions over unsafe code that has been
audited. Wrapping unsafe code in a safe abstraction prevents uses of unsafe
from leaking out into all the places that you or your users might want to use
the functionality implemented with unsafe
code, because using a safe
abstraction is safe.
Let’s look at each of the five unsafe superpowers in turn. We’ll also look at some abstractions that provide a safe interface to unsafe code.
Dereferencing a Raw Pointer
In Chapter 4, in the “Dangling References” section, we mentioned that the compiler ensures references are always
valid. Unsafe Rust has two new types called raw pointers that are similar to
references. As with references, raw pointers can be immutable or mutable and
are written as *const T
and *mut T
, respectively. The asterisk isn’t the
dereference operator; it’s part of the type name. In the context of raw
pointers, immutable means that the pointer can’t be directly assigned to
after being dereferenced.
Different from references and smart pointers, raw pointers:
- Are allowed to ignore the borrowing rules by having both immutable and mutable pointers or multiple mutable pointers to the same location
- Aren’t guaranteed to point to valid memory
- Are allowed to be null
- Don’t implement any automatic cleanup
By opting out of having Rust enforce these guarantees, you can give up guaranteed safety in exchange for greater performance or the ability to interface with another language or hardware where Rust’s guarantees don’t apply.
Listing 19-1 shows how to create an immutable and a mutable raw pointer from references.
fn main() { let mut num = 5; let r1 = &num as *const i32; let r2 = &mut num as *mut i32; }
Notice that we don’t include the unsafe
keyword in this code. We can create
raw pointers in safe code; we just can’t dereference raw pointers outside an
unsafe block, as you’ll see in a bit.
We’ve created raw pointers by using as
to cast an immutable and a mutable
reference into their corresponding raw pointer types. Because we created them
directly from references guaranteed to be valid, we know these particular raw
pointers are valid, but we can’t make that assumption about just any raw
pointer.
To demonstrate this, next we’ll create a raw pointer whose validity we can’t be so certain of. Listing 19-2 shows how to create a raw pointer to an arbitrary location in memory. Trying to use arbitrary memory is undefined: there might be data at that address or there might not, the compiler might optimize the code so there is no memory access, or the program might error with a segmentation fault. Usually, there is no good reason to write code like this, but it is possible.
fn main() { let address = 0x012345usize; let r = address as *const i32; }
Recall that we can create raw pointers in safe code, but we can’t dereference
raw pointers and read the data being pointed to. In Listing 19-3, we use the
dereference operator *
on a raw pointer that requires an unsafe
block.
fn main() { let mut num = 5; let r1 = &num as *const i32; let r2 = &mut num as *mut i32; unsafe { println!("r1 is: {}", *r1); println!("r2 is: {}", *r2); } }
Creating a pointer does no harm; it’s only when we try to access the value that it points at that we might end up dealing with an invalid value.
Note also that in Listing 19-1 and 19-3, we created *const i32
and *mut i32
raw pointers that both pointed to the same memory location, where num
is
stored. If we instead tried to create an immutable and a mutable reference to
num
, the code would not have compiled because Rust’s ownership rules don’t
allow a mutable reference at the same time as any immutable references. With
raw pointers, we can create a mutable pointer and an immutable pointer to the
same location and change data through the mutable pointer, potentially creating
a data race. Be careful!
With all of these dangers, why would you ever use raw pointers? One major use case is when interfacing with C code, as you’ll see in the next section, “Calling an Unsafe Function or Method.” Another case is when building up safe abstractions that the borrow checker doesn’t understand. We’ll introduce unsafe functions and then look at an example of a safe abstraction that uses unsafe code.
Calling an Unsafe Function or Method
The second type of operation you can perform in an unsafe block is calling
unsafe functions. Unsafe functions and methods look exactly like regular
functions and methods, but they have an extra unsafe
before the rest of the
definition. The unsafe
keyword in this context indicates the function has
requirements we need to uphold when we call this function, because Rust can’t
guarantee we’ve met these requirements. By calling an unsafe function within an
unsafe
block, we’re saying that we’ve read this function’s documentation and
take responsibility for upholding the function’s contracts.
Here is an unsafe function named dangerous
that doesn’t do anything in its
body:
fn main() { unsafe fn dangerous() {} unsafe { dangerous(); } }
We must call the dangerous
function within a separate unsafe
block. If we
try to call dangerous
without the unsafe
block, we’ll get an error:
$ cargo run
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
--> src/main.rs:4:5
|
4 | dangerous();
| ^^^^^^^^^^^ call to unsafe function
|
= note: consult the function's documentation for information on how to avoid undefined behavior
For more information about this error, try `rustc --explain E0133`.
error: could not compile `unsafe-example` due to previous error
With the unsafe
block, we’re asserting to Rust that we’ve read the function’s
documentation, we understand how to use it properly, and we’ve verified that
we’re fulfilling the contract of the function.
Bodies of unsafe functions are effectively unsafe
blocks, so to perform other
unsafe operations within an unsafe function, we don’t need to add another
unsafe
block.
Creating a Safe Abstraction over Unsafe Code
Just because a function contains unsafe code doesn’t mean we need to mark the
entire function as unsafe. In fact, wrapping unsafe code in a safe function is
a common abstraction. As an example, let’s study the split_at_mut
function
from the standard library, which requires some unsafe code. We’ll explore how
we might implement it. This safe method is defined on mutable slices: it takes
one slice and makes it two by splitting the slice at the index given as an
argument. Listing 19-4 shows how to use split_at_mut
.
fn main() { let mut v = vec![1, 2, 3, 4, 5, 6]; let r = &mut v[..]; let (a, b) = r.split_at_mut(3); assert_eq!(a, &mut [1, 2, 3]); assert_eq!(b, &mut [4, 5, 6]); }
We can’t implement this function using only safe Rust. An attempt might look
something like Listing 19-5, which won’t compile. For simplicity, we’ll
implement split_at_mut
as a function rather than a method and only for slices
of i32
values rather than for a generic type T
.
fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = values.len();
assert!(mid <= len);
(&mut values[..mid], &mut values[mid..])
}
fn main() {
let mut vector = vec![1, 2, 3, 4, 5, 6];
let (left, right) = split_at_mut(&mut vector, 3);
}
This function first gets the total length of the slice. Then it asserts that the index given as a parameter is within the slice by checking whether it’s less than or equal to the length. The assertion means that if we pass an index that is greater than the length to split the slice at, the function will panic before it attempts to use that index.
Then we return two mutable slices in a tuple: one from the start of the
original slice to the mid
index and another from mid
to the end of the
slice.
When we try to compile the code in Listing 19-5, we’ll get an error.
$ cargo run
Compiling unsafe-example v0.1.0 (file:///projects/unsafe-example)
error[E0499]: cannot borrow `*values` as mutable more than once at a time
--> src/main.rs:6:31
|
1 | fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
| - let's call the lifetime of this reference `'1`
...
6 | (&mut values[..mid], &mut values[mid..])
| --------------------------^^^^^^--------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*values` is borrowed for `'1`
For more information about this error, try `rustc --explain E0499`.
error: could not compile `unsafe-example` due to previous error
Rust’s borrow checker can’t understand that we’re borrowing different parts of the slice; it only knows that we’re borrowing from the same slice twice. Borrowing different parts of a slice is fundamentally okay because the two slices aren’t overlapping, but Rust isn’t smart enough to know this. When we know code is okay, but Rust doesn’t, it’s time to reach for unsafe code.
Listing 19-6 shows how to use an unsafe
block, a raw pointer, and some calls
to unsafe functions to make the implementation of split_at_mut
work.
use std::slice; fn split_at_mut(values: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { let len = values.len(); let ptr = values.as_mut_ptr(); assert!(mid <= len); unsafe { ( slice::from_raw_parts_mut(ptr, mid), slice::from_raw_parts_mut(ptr.add(mid), len - mid), ) } } fn main() { let mut vector = vec![1, 2, 3, 4, 5, 6]; let (left, right) = split_at_mut(&mut vector, 3); }
Recall from “The Slice Type” section in
Chapter 4 that slices are a pointer to some data and the length of the slice.
We use the len
method to get the length of a slice and the as_mut_ptr
method to access the raw pointer of a slice. In this case, because we have a
mutable slice to i32
values, as_mut_ptr
returns a raw pointer with the type
*mut i32
, which we’ve stored in the variable ptr
.
We keep the assertion that the mid
index is within the slice. Then we get to
the unsafe code: the slice::from_raw_parts_mut
function takes a raw pointer
and a length, and it creates a slice. We use this function to create a slice
that starts from ptr
and is mid
items long. Then we call the add
method on ptr
with mid
as an argument to get a raw pointer that starts at
mid
, and we create a slice using that pointer and the remaining number of
items after mid
as the length.
The function slice::from_raw_parts_mut
is unsafe because it takes a raw
pointer and must trust that this pointer is valid. The add
method on raw
pointers is also unsafe, because it must trust that the offset location is also
a valid pointer. Therefore, we had to put an unsafe
block around our calls to
slice::from_raw_parts_mut
and add
so we could call them. By looking at
the code and by adding the assertion that mid
must be less than or equal to
len
, we can tell that all the raw pointers used within the unsafe
block
will be valid pointers to data within the slice. This is an acceptable and
appropriate use of unsafe
.
Note that we don’t need to mark the resulting split_at_mut
function as
unsafe
, and we can call this function from safe Rust. We’ve created a safe
abstraction to the unsafe code with an implementation of the function that uses
unsafe
code in a safe way, because it creates only valid pointers from the
data this function has access to.
In contrast, the use of slice::from_raw_parts_mut
in Listing 19-7 would
likely crash when the slice is used. This code takes an arbitrary memory
location and creates a slice 10,000 items long.
fn main() { use std::slice; let address = 0x01234usize; let r = address as *mut i32; let values: &[i32] = unsafe { slice::from_raw_parts_mut(r, 10000) }; }
We don’t own the memory at this arbitrary location, and there is no guarantee
that the slice this code creates contains valid i32
values. Attempting to use
values
as though it’s a valid slice results in undefined behavior.
Using extern
Functions to Call External Code
Sometimes, your Rust code might need to interact with code written in another
language. For this, Rust has the keyword extern
that facilitates the creation
and use of a Foreign Function Interface (FFI). An FFI is a way for a
programming language to define functions and enable a different (foreign)
programming language to call those functions.
Listing 19-8 demonstrates how to set up an integration with the abs
function
from the C standard library. Functions declared within extern
blocks are
always unsafe to call from Rust code. The reason is that other languages don’t
enforce Rust’s rules and guarantees, and Rust can’t check them, so
responsibility falls on the programmer to ensure safety.
Filename: src/main.rs
extern "C" { fn abs(input: i32) -> i32; } fn main() { unsafe { println!("Absolute value of -3 according to C: {}", abs(-3)); } }
Within the extern "C"
block, we list the names and signatures of external
functions from another language we want to call. The "C"
part defines which
application binary interface (ABI) the external function uses: the ABI
defines how to call the function at the assembly level. The "C"
ABI is the
most common and follows the C programming language’s ABI.
Calling Rust Functions from Other Languages
We can also use
extern
to create an interface that allows other languages to call Rust functions. Instead of creating a wholeextern
block, we add theextern
keyword and specify the ABI to use just before thefn
keyword for the relevant function. We also need to add a#[no_mangle]
annotation to tell the Rust compiler not to mangle the name of this function. Mangling is when a compiler changes the name we’ve given a function to a different name that contains more information for other parts of the compilation process to consume but is less human readable. Every programming language compiler mangles names slightly differently, so for a Rust function to be nameable by other languages, we must disable the Rust compiler’s name mangling.In the following example, we make the
call_from_c
function accessible from C code, after it’s compiled to a shared library and linked from C:#![allow(unused)] fn main() { #[no_mangle] pub extern "C" fn call_from_c() { println!("Just called a Rust function from C!"); } }
This usage of
extern
does not requireunsafe
.
Accessing or Modifying a Mutable Static Variable
In this book, we’ve not yet talked about global variables, which Rust does support but can be problematic with Rust’s ownership rules. If two threads are accessing the same mutable global variable, it can cause a data race.
In Rust, global variables are called static variables. Listing 19-9 shows an example declaration and use of a static variable with a string slice as a value.
Filename: src/main.rs
static HELLO_WORLD: &str = "Hello, world!"; fn main() { println!("name is: {}", HELLO_WORLD); }
Static variables are similar to constants, which we discussed in the
“Differences Between Variables and
Constants” section
in Chapter 3. The names of static variables are in SCREAMING_SNAKE_CASE
by
convention. Static variables can only store references with the 'static
lifetime, which means the Rust compiler can figure out the lifetime and we
aren’t required to annotate it explicitly. Accessing an immutable static
variable is safe.
A subtle difference between constants and immutable static variables is that
values in a static variable have a fixed address in memory. Using the value
will always access the same data. Constants, on the other hand, are allowed to
duplicate their data whenever they’re used. Another difference is that static
variables can be mutable. Accessing and modifying mutable static variables is
unsafe. Listing 19-10 shows how to declare, access, and modify a mutable
static variable named COUNTER
.
Filename: src/main.rs
static mut COUNTER: u32 = 0; fn add_to_count(inc: u32) { unsafe { COUNTER += inc; } } fn main() { add_to_count(3); unsafe { println!("COUNTER: {}", COUNTER); } }
As with regular variables, we specify mutability using the mut
keyword. Any
code that reads or writes from COUNTER
must be within an unsafe
block. This
code compiles and prints COUNTER: 3
as we would expect because it’s single
threaded. Having multiple threads access COUNTER
would likely result in data
races.
With mutable data that is globally accessible, it’s difficult to ensure there are no data races, which is why Rust considers mutable static variables to be unsafe. Where possible, it’s preferable to use the concurrency techniques and thread-safe smart pointers we discussed in Chapter 16 so the compiler checks that data accessed from different threads is done safely.
Implementing an Unsafe Trait
We can use unsafe
to implement an unsafe trait. A trait is unsafe when at
least one of its methods has some invariant that the compiler can’t verify. We
declare that a trait is unsafe
by adding the unsafe
keyword before trait
and marking the implementation of the trait as unsafe
too, as shown in
Listing 19-11.
unsafe trait Foo { // methods go here } unsafe impl Foo for i32 { // method implementations go here } fn main() {}
By using unsafe impl
, we’re promising that we’ll uphold the invariants that
the compiler can’t verify.
As an example, recall the Sync
and Send
marker traits we discussed in the
“Extensible Concurrency with the Sync
and Send
Traits”
section in Chapter 16: the compiler implements these traits automatically if
our types are composed entirely of Send
and Sync
types. If we implement a
type that contains a type that is not Send
or Sync
, such as raw pointers,
and we want to mark that type as Send
or Sync
, we must use unsafe
. Rust
can’t verify that our type upholds the guarantees that it can be safely sent
across threads or accessed from multiple threads; therefore, we need to do
those checks manually and indicate as such with unsafe
.
Accessing Fields of a Union
The final action that works only with unsafe
is accessing fields of a
union. A union
is similar to a struct
, but only one declared field is
used in a particular instance at one time. Unions are primarily used to
interface with unions in C code. Accessing union fields is unsafe because Rust
can’t guarantee the type of the data currently being stored in the union
instance. You can learn more about unions in the Rust Reference.
When to Use Unsafe Code
Using unsafe
to take one of the five actions (superpowers) just discussed
isn’t wrong or even frowned upon. But it is trickier to get unsafe
code
correct because the compiler can’t help uphold memory safety. When you have a
reason to use unsafe
code, you can do so, and having the explicit unsafe
annotation makes it easier to track down the source of problems when they occur.
Advanced Traits
We first covered traits in the “Traits: Defining Shared Behavior” section of Chapter 10, but we didn’t discuss the more advanced details. Now that you know more about Rust, we can get into the nitty-gritty.
Specifying Placeholder Types in Trait Definitions with Associated Types
Associated types connect a type placeholder with a trait such that the trait method definitions can use these placeholder types in their signatures. The implementor of a trait will specify the concrete type to be used instead of the placeholder type for the particular implementation. That way, we can define a trait that uses some types without needing to know exactly what those types are until the trait is implemented.
We’ve described most of the advanced features in this chapter as being rarely needed. Associated types are somewhere in the middle: they’re used more rarely than features explained in the rest of the book but more commonly than many of the other features discussed in this chapter.
One example of a trait with an associated type is the Iterator
trait that the
standard library provides. The associated type is named Item
and stands in
for the type of the values the type implementing the Iterator
trait is
iterating over. The definition of the Iterator
trait is as shown in Listing
19-12.
pub trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
The type Item
is a placeholder, and the next
method’s definition shows that
it will return values of type Option<Self::Item>
. Implementors of the
Iterator
trait will specify the concrete type for Item
, and the next
method will return an Option
containing a value of that concrete type.
Associated types might seem like a similar concept to generics, in that the
latter allow us to define a function without specifying what types it can
handle. To examine the difference between the two concepts, we’ll look at an
implementation of the Iterator
trait on a type named Counter
that specifies
the Item
type is u32
:
Filename: src/lib.rs
struct Counter {
count: u32,
}
impl Counter {
fn new() -> Counter {
Counter { count: 0 }
}
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
// --snip--
if self.count < 5 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
This syntax seems comparable to that of generics. So why not just define the
Iterator
trait with generics, as shown in Listing 19-13?
pub trait Iterator<T> {
fn next(&mut self) -> Option<T>;
}
The difference is that when using generics, as in Listing 19-13, we must
annotate the types in each implementation; because we can also implement
Iterator<String> for Counter
or any other type, we could have multiple
implementations of Iterator
for Counter
. In other words, when a trait has a
generic parameter, it can be implemented for a type multiple times, changing
the concrete types of the generic type parameters each time. When we use the
next
method on Counter
, we would have to provide type annotations to
indicate which implementation of Iterator
we want to use.
With associated types, we don’t need to annotate types because we can’t
implement a trait on a type multiple times. In Listing 19-12 with the
definition that uses associated types, we can only choose what the type of
Item
will be once, because there can only be one impl Iterator for Counter
.
We don’t have to specify that we want an iterator of u32
values everywhere
that we call next
on Counter
.
Associated types also become part of the trait’s contract: implementors of the trait must provide a type to stand in for the associated type placeholder. Associated types often have a name that describes how the type will be used, and documenting the associated type in the API documentation is good practice.
Default Generic Type Parameters and Operator Overloading
When we use generic type parameters, we can specify a default concrete type for
the generic type. This eliminates the need for implementors of the trait to
specify a concrete type if the default type works. You specify a default type
when declaring a generic type with the <PlaceholderType=ConcreteType>
syntax.
A great example of a situation where this technique is useful is with operator
overloading, in which you customize the behavior of an operator (such as +
)
in particular situations.
Rust doesn’t allow you to create your own operators or overload arbitrary
operators. But you can overload the operations and corresponding traits listed
in std::ops
by implementing the traits associated with the operator. For
example, in Listing 19-14 we overload the +
operator to add two Point
instances together. We do this by implementing the Add
trait on a Point
struct:
Filename: src/main.rs
use std::ops::Add; #[derive(Debug, Copy, Clone, PartialEq)] struct Point { x: i32, y: i32, } impl Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y, } } } fn main() { assert_eq!( Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, Point { x: 3, y: 3 } ); }
The add
method adds the x
values of two Point
instances and the y
values of two Point
instances to create a new Point
. The Add
trait has an
associated type named Output
that determines the type returned from the add
method.
The default generic type in this code is within the Add
trait. Here is its
definition:
#![allow(unused)] fn main() { trait Add<Rhs=Self> { type Output; fn add(self, rhs: Rhs) -> Self::Output; } }
This code should look generally familiar: a trait with one method and an
associated type. The new part is Rhs=Self
: this syntax is called default
type parameters. The Rhs
generic type parameter (short for “right hand
side”) defines the type of the rhs
parameter in the add
method. If we don’t
specify a concrete type for Rhs
when we implement the Add
trait, the type
of Rhs
will default to Self
, which will be the type we’re implementing
Add
on.
When we implemented Add
for Point
, we used the default for Rhs
because we
wanted to add two Point
instances. Let’s look at an example of implementing
the Add
trait where we want to customize the Rhs
type rather than using the
default.
We have two structs, Millimeters
and Meters
, holding values in different
units. This thin wrapping of an existing type in another struct is known as the
newtype pattern, which we describe in more detail in the “Using the Newtype
Pattern to Implement External Traits on External Types” section. We want to add values in millimeters to values in meters and have
the implementation of Add
do the conversion correctly. We can implement Add
for Millimeters
with Meters
as the Rhs
, as shown in Listing 19-15.
Filename: src/lib.rs
use std::ops::Add;
struct Millimeters(u32);
struct Meters(u32);
impl Add<Meters> for Millimeters {
type Output = Millimeters;
fn add(self, other: Meters) -> Millimeters {
Millimeters(self.0 + (other.0 * 1000))
}
}
To add Millimeters
and Meters
, we specify impl Add<Meters>
to set the
value of the Rhs
type parameter instead of using the default of Self
.
You’ll use default type parameters in two main ways:
- To extend a type without breaking existing code
- To allow customization in specific cases most users won’t need
The standard library’s Add
trait is an example of the second purpose:
usually, you’ll add two like types, but the Add
trait provides the ability to
customize beyond that. Using a default type parameter in the Add
trait
definition means you don’t have to specify the extra parameter most of the
time. In other words, a bit of implementation boilerplate isn’t needed, making
it easier to use the trait.
The first purpose is similar to the second but in reverse: if you want to add a type parameter to an existing trait, you can give it a default to allow extension of the functionality of the trait without breaking the existing implementation code.
Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name
Nothing in Rust prevents a trait from having a method with the same name as another trait’s method, nor does Rust prevent you from implementing both traits on one type. It’s also possible to implement a method directly on the type with the same name as methods from traits.
When calling methods with the same name, you’ll need to tell Rust which one you
want to use. Consider the code in Listing 19-16 where we’ve defined two traits,
Pilot
and Wizard
, that both have a method called fly
. We then implement
both traits on a type Human
that already has a method named fly
implemented
on it. Each fly
method does something different.
Filename: src/main.rs
trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*waving arms furiously*"); } } fn main() {}
When we call fly
on an instance of Human
, the compiler defaults to calling
the method that is directly implemented on the type, as shown in Listing 19-17.
Filename: src/main.rs
trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*waving arms furiously*"); } } fn main() { let person = Human; person.fly(); }
Running this code will print *waving arms furiously*
, showing that Rust
called the fly
method implemented on Human
directly.
To call the fly
methods from either the Pilot
trait or the Wizard
trait,
we need to use more explicit syntax to specify which fly
method we mean.
Listing 19-18 demonstrates this syntax.
Filename: src/main.rs
trait Pilot { fn fly(&self); } trait Wizard { fn fly(&self); } struct Human; impl Pilot for Human { fn fly(&self) { println!("This is your captain speaking."); } } impl Wizard for Human { fn fly(&self) { println!("Up!"); } } impl Human { fn fly(&self) { println!("*waving arms furiously*"); } } fn main() { let person = Human; Pilot::fly(&person); Wizard::fly(&person); person.fly(); }
Specifying the trait name before the method name clarifies to Rust which
implementation of fly
we want to call. We could also write
Human::fly(&person)
, which is equivalent to the person.fly()
that we used
in Listing 19-18, but this is a bit longer to write if we don’t need to
disambiguate.
Running this code prints the following:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.46s
Running `target/debug/traits-example`
This is your captain speaking.
Up!
*waving arms furiously*
Because the fly
method takes a self
parameter, if we had two types that
both implement one trait, Rust could figure out which implementation of a
trait to use based on the type of self
.
However, associated functions that are not methods don’t have a self
parameter. When there are multiple types or traits that define non-method
functions with the same function name, Rust doesn't always know which type you
mean unless you use fully qualified syntax. For example, in Listing 19-19 we
create a trait for an animal shelter that wants to name all baby dogs Spot.
We make an Animal
trait with an associated non-method function baby_name
.
The Animal
trait is implemented for the struct Dog
, on which we also
provide an associated non-method function baby_name
directly.
Filename: src/main.rs
trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { println!("A baby dog is called a {}", Dog::baby_name()); }
We implement the code for naming all puppies Spot in the baby_name
associated
function that is defined on Dog
. The Dog
type also implements the trait
Animal
, which describes characteristics that all animals have. Baby dogs are
called puppies, and that is expressed in the implementation of the Animal
trait on Dog
in the baby_name
function associated with the Animal
trait.
In main
, we call the Dog::baby_name
function, which calls the associated
function defined on Dog
directly. This code prints the following:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.54s
Running `target/debug/traits-example`
A baby dog is called a Spot
This output isn’t what we wanted. We want to call the baby_name
function that
is part of the Animal
trait that we implemented on Dog
so the code prints
A baby dog is called a puppy
. The technique of specifying the trait name that
we used in Listing 19-18 doesn’t help here; if we change main
to the code in
Listing 19-20, we’ll get a compilation error.
Filename: src/main.rs
trait Animal {
fn baby_name() -> String;
}
struct Dog;
impl Dog {
fn baby_name() -> String {
String::from("Spot")
}
}
impl Animal for Dog {
fn baby_name() -> String {
String::from("puppy")
}
}
fn main() {
println!("A baby dog is called a {}", Animal::baby_name());
}
Because Animal::baby_name
doesn’t have a self
parameter, and there could be
other types that implement the Animal
trait, Rust can’t figure out which
implementation of Animal::baby_name
we want. We’ll get this compiler error:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> src/main.rs:20:43
|
2 | fn baby_name() -> String;
| ------------------------- `Animal::baby_name` defined here
...
20 | println!("A baby dog is called a {}", Animal::baby_name());
| ^^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use the fully-qualified path to the only available implementation
|
20 | println!("A baby dog is called a {}", <Dog as Animal>::baby_name());
| +++++++ +
For more information about this error, try `rustc --explain E0790`.
error: could not compile `traits-example` due to previous error
To disambiguate and tell Rust that we want to use the implementation of
Animal
for Dog
as opposed to the implementation of Animal
for some other
type, we need to use fully qualified syntax. Listing 19-21 demonstrates how to
use fully qualified syntax.
Filename: src/main.rs
trait Animal { fn baby_name() -> String; } struct Dog; impl Dog { fn baby_name() -> String { String::from("Spot") } } impl Animal for Dog { fn baby_name() -> String { String::from("puppy") } } fn main() { println!("A baby dog is called a {}", <Dog as Animal>::baby_name()); }
We’re providing Rust with a type annotation within the angle brackets, which
indicates we want to call the baby_name
method from the Animal
trait as
implemented on Dog
by saying that we want to treat the Dog
type as an
Animal
for this function call. This code will now print what we want:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
Finished dev [unoptimized + debuginfo] target(s) in 0.48s
Running `target/debug/traits-example`
A baby dog is called a puppy
In general, fully qualified syntax is defined as follows:
<Type as Trait>::function(receiver_if_method, next_arg, ...);
For associated functions that aren’t methods, there would not be a receiver
:
there would only be the list of other arguments. You could use fully qualified
syntax everywhere that you call functions or methods. However, you’re allowed
to omit any part of this syntax that Rust can figure out from other information
in the program. You only need to use this more verbose syntax in cases where
there are multiple implementations that use the same name and Rust needs help
to identify which implementation you want to call.
Using Supertraits to Require One Trait’s Functionality Within Another Trait
Sometimes, you might write a trait definition that depends on another trait: for a type to implement the first trait, you want to require that type to also implement the second trait. You would do this so that your trait definition can make use of the associated items of the second trait. The trait your trait definition is relying on is called a supertrait of your trait.
For example, let’s say we want to make an OutlinePrint
trait with an
outline_print
method that will print a given value formatted so that it's
framed in asterisks. That is, given a Point
struct that implements the
standard library trait Display
to result in (x, y)
, when we call
outline_print
on a Point
instance that has 1
for x
and 3
for y
, it
should print the following:
**********
* *
* (1, 3) *
* *
**********
In the implementation of the outline_print
method, we want to use the
Display
trait’s functionality. Therefore, we need to specify that the
OutlinePrint
trait will work only for types that also implement Display
and
provide the functionality that OutlinePrint
needs. We can do that in the
trait definition by specifying OutlinePrint: Display
. This technique is
similar to adding a trait bound to the trait. Listing 19-22 shows an
implementation of the OutlinePrint
trait.
Filename: src/main.rs
use std::fmt; trait OutlinePrint: fmt::Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}", "*".repeat(len + 4)); println!("*{}*", " ".repeat(len + 2)); println!("* {} *", output); println!("*{}*", " ".repeat(len + 2)); println!("{}", "*".repeat(len + 4)); } } fn main() {}
Because we’ve specified that OutlinePrint
requires the Display
trait, we
can use the to_string
function that is automatically implemented for any type
that implements Display
. If we tried to use to_string
without adding a
colon and specifying the Display
trait after the trait name, we’d get an
error saying that no method named to_string
was found for the type &Self
in
the current scope.
Let’s see what happens when we try to implement OutlinePrint
on a type that
doesn’t implement Display
, such as the Point
struct:
Filename: src/main.rs
use std::fmt;
trait OutlinePrint: fmt::Display {
fn outline_print(&self) {
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {} *", output);
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
struct Point {
x: i32,
y: i32,
}
impl OutlinePrint for Point {}
fn main() {
let p = Point { x: 1, y: 3 };
p.outline_print();
}
We get an error saying that Display
is required but not implemented:
$ cargo run
Compiling traits-example v0.1.0 (file:///projects/traits-example)
error[E0277]: `Point` doesn't implement `std::fmt::Display`
--> src/main.rs:20:6
|
20 | impl OutlinePrint for Point {}
| ^^^^^^^^^^^^ `Point` cannot be formatted with the default formatter
|
= help: the trait `std::fmt::Display` is not implemented for `Point`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
note: required by a bound in `OutlinePrint`
--> src/main.rs:3:21
|
3 | trait OutlinePrint: fmt::Display {
| ^^^^^^^^^^^^ required by this bound in `OutlinePrint`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `traits-example` due to previous error
To fix this, we implement Display
on Point
and satisfy the constraint that
OutlinePrint
requires, like so:
Filename: src/main.rs
trait OutlinePrint: fmt::Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}", "*".repeat(len + 4)); println!("*{}*", " ".repeat(len + 2)); println!("* {} *", output); println!("*{}*", " ".repeat(len + 2)); println!("{}", "*".repeat(len + 4)); } } struct Point { x: i32, y: i32, } impl OutlinePrint for Point {} use std::fmt; impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) } } fn main() { let p = Point { x: 1, y: 3 }; p.outline_print(); }
Then implementing the OutlinePrint
trait on Point
will compile
successfully, and we can call outline_print
on a Point
instance to display
it within an outline of asterisks.
Using the Newtype Pattern to Implement External Traits on External Types
In Chapter 10 in the “Implementing a Trait on a Type” section, we mentioned the orphan rule that states we’re only allowed to implement a trait on a type if either the trait or the type are local to our crate. It’s possible to get around this restriction using the newtype pattern, which involves creating a new type in a tuple struct. (We covered tuple structs in the “Using Tuple Structs without Named Fields to Create Different Types” section of Chapter 5.) The tuple struct will have one field and be a thin wrapper around the type we want to implement a trait for. Then the wrapper type is local to our crate, and we can implement the trait on the wrapper. Newtype is a term that originates from the Haskell programming language. There is no runtime performance penalty for using this pattern, and the wrapper type is elided at compile time.
As an example, let’s say we want to implement Display
on Vec<T>
, which the
orphan rule prevents us from doing directly because the Display
trait and the
Vec<T>
type are defined outside our crate. We can make a Wrapper
struct
that holds an instance of Vec<T>
; then we can implement Display
on
Wrapper
and use the Vec<T>
value, as shown in Listing 19-23.
Filename: src/main.rs
use std::fmt; struct Wrapper(Vec<String>); impl fmt::Display for Wrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}]", self.0.join(", ")) } } fn main() { let w = Wrapper(vec![String::from("hello"), String::from("world")]); println!("w = {}", w); }
The implementation of Display
uses self.0
to access the inner Vec<T>
,
because Wrapper
is a tuple struct and Vec<T>
is the item at index 0 in the
tuple. Then we can use the functionality of the Display
type on Wrapper
.
The downside of using this technique is that Wrapper
is a new type, so it
doesn’t have the methods of the value it’s holding. We would have to implement
all the methods of Vec<T>
directly on Wrapper
such that the methods
delegate to self.0
, which would allow us to treat Wrapper
exactly like a
Vec<T>
. If we wanted the new type to have every method the inner type has,
implementing the Deref
trait (discussed in Chapter 15 in the “Treating Smart
Pointers Like Regular References with the Deref
Trait” section) on the Wrapper
to return
the inner type would be a solution. If we don’t want the Wrapper
type to have
all the methods of the inner type—for example, to restrict the Wrapper
type’s
behavior—we would have to implement just the methods we do want manually.
This newtype pattern is also useful even when traits are not involved. Let’s switch focus and look at some advanced ways to interact with Rust’s type system.
Advanced Types
The Rust type system has some features that we’ve so far mentioned but haven’t
yet discussed. We’ll start by discussing newtypes in general as we examine why
newtypes are useful as types. Then we’ll move on to type aliases, a feature
similar to newtypes but with slightly different semantics. We’ll also discuss
the !
type and dynamically sized types.
Using the Newtype Pattern for Type Safety and Abstraction
Note: This section assumes you’ve read the earlier section “Using the Newtype Pattern to Implement External Traits on External Types.”
The newtype pattern is also useful for tasks beyond those we’ve discussed so
far, including statically enforcing that values are never confused and
indicating the units of a value. You saw an example of using newtypes to
indicate units in Listing 19-15: recall that the Millimeters
and Meters
structs wrapped u32
values in a newtype. If we wrote a function with a
parameter of type Millimeters
, we couldn’t compile a program that
accidentally tried to call that function with a value of type Meters
or a
plain u32
.
We can also use the newtype pattern to abstract away some implementation details of a type: the new type can expose a public API that is different from the API of the private inner type.
Newtypes can also hide internal implementation. For example, we could provide a
People
type to wrap a HashMap<i32, String>
that stores a person’s ID
associated with their name. Code using People
would only interact with the
public API we provide, such as a method to add a name string to the People
collection; that code wouldn’t need to know that we assign an i32
ID to names
internally. The newtype pattern is a lightweight way to achieve encapsulation
to hide implementation details, which we discussed in the “Encapsulation that
Hides Implementation
Details”
section of Chapter 17.
Creating Type Synonyms with Type Aliases
Rust provides the ability to declare a type alias to give an existing type
another name. For this we use the type
keyword. For example, we can create
the alias Kilometers
to i32
like so:
fn main() { type Kilometers = i32; let x: i32 = 5; let y: Kilometers = 5; println!("x + y = {}", x + y); }
Now, the alias Kilometers
is a synonym for i32
; unlike the Millimeters
and Meters
types we created in Listing 19-15, Kilometers
is not a separate,
new type. Values that have the type Kilometers
will be treated the same as
values of type i32
:
fn main() { type Kilometers = i32; let x: i32 = 5; let y: Kilometers = 5; println!("x + y = {}", x + y); }
Because Kilometers
and i32
are the same type, we can add values of both
types and we can pass Kilometers
values to functions that take i32
parameters. However, using this method, we don’t get the type checking benefits
that we get from the newtype pattern discussed earlier. In other words, if we
mix up Kilometers
and i32
values somewhere, the compiler will not give us
an error.
The main use case for type synonyms is to reduce repetition. For example, we might have a lengthy type like this:
Box<dyn Fn() + Send + 'static>
Writing this lengthy type in function signatures and as type annotations all over the code can be tiresome and error prone. Imagine having a project full of code like that in Listing 19-24.
fn main() { let f: Box<dyn Fn() + Send + 'static> = Box::new(|| println!("hi")); fn takes_long_type(f: Box<dyn Fn() + Send + 'static>) { // --snip-- } fn returns_long_type() -> Box<dyn Fn() + Send + 'static> { // --snip-- Box::new(|| ()) } }
A type alias makes this code more manageable by reducing the repetition. In
Listing 19-25, we’ve introduced an alias named Thunk
for the verbose type and
can replace all uses of the type with the shorter alias Thunk
.
fn main() { type Thunk = Box<dyn Fn() + Send + 'static>; let f: Thunk = Box::new(|| println!("hi")); fn takes_long_type(f: Thunk) { // --snip-- } fn returns_long_type() -> Thunk { // --snip-- Box::new(|| ()) } }
This code is much easier to read and write! Choosing a meaningful name for a type alias can help communicate your intent as well (thunk is a word for code to be evaluated at a later time, so it’s an appropriate name for a closure that gets stored).
Type aliases are also commonly used with the Result<T, E>
type for reducing
repetition. Consider the std::io
module in the standard library. I/O
operations often return a Result<T, E>
to handle situations when operations
fail to work. This library has a std::io::Error
struct that represents all
possible I/O errors. Many of the functions in std::io
will be returning
Result<T, E>
where the E
is std::io::Error
, such as these functions in
the Write
trait:
use std::fmt;
use std::io::Error;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize, Error>;
fn flush(&mut self) -> Result<(), Error>;
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<(), Error>;
}
The Result<..., Error>
is repeated a lot. As such, std::io
has this type
alias declaration:
use std::fmt;
type Result<T> = std::result::Result<T, std::io::Error>;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize>;
fn flush(&mut self) -> Result<()>;
fn write_all(&mut self, buf: &[u8]) -> Result<()>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;
}
Because this declaration is in the std::io
module, we can use the fully
qualified alias std::io::Result<T>
; that is, a Result<T, E>
with the E
filled in as std::io::Error
. The Write
trait function signatures end up
looking like this:
use std::fmt;
type Result<T> = std::result::Result<T, std::io::Error>;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize>;
fn flush(&mut self) -> Result<()>;
fn write_all(&mut self, buf: &[u8]) -> Result<()>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;
}
The type alias helps in two ways: it makes code easier to write and it gives
us a consistent interface across all of std::io
. Because it’s an alias, it’s
just another Result<T, E>
, which means we can use any methods that work on
Result<T, E>
with it, as well as special syntax like the ?
operator.
The Never Type that Never Returns
Rust has a special type named !
that’s known in type theory lingo as the
empty type because it has no values. We prefer to call it the never type
because it stands in the place of the return type when a function will never
return. Here is an example:
fn bar() -> ! {
// --snip--
panic!();
}
This code is read as “the function bar
returns never.” Functions that return
never are called diverging functions. We can’t create values of the type !
so bar
can never possibly return.
But what use is a type you can never create values for? Recall the code from Listing 2-5, part of the number guessing game; we’ve reproduced a bit of it here in Listing 19-26.
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..=100);
println!("The secret number is: {secret_number}");
loop {
println!("Please input your guess.");
let mut guess = String::new();
// --snip--
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
// --snip--
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
At the time, we skipped over some details in this code. In Chapter 6 in “The
match
Control Flow Operator”
section, we discussed that match
arms must all return the same type. So, for
example, the following code doesn’t work:
fn main() {
let guess = "3";
let guess = match guess.trim().parse() {
Ok(_) => 5,
Err(_) => "hello",
};
}
The type of guess
in this code would have to be an integer and a string,
and Rust requires that guess
have only one type. So what does continue
return? How were we allowed to return a u32
from one arm and have another arm
that ends with continue
in Listing 19-26?
As you might have guessed, continue
has a !
value. That is, when Rust
computes the type of guess
, it looks at both match arms, the former with a
value of u32
and the latter with a !
value. Because !
can never have a
value, Rust decides that the type of guess
is u32
.
The formal way of describing this behavior is that expressions of type !
can
be coerced into any other type. We’re allowed to end this match
arm with
continue
because continue
doesn’t return a value; instead, it moves control
back to the top of the loop, so in the Err
case, we never assign a value to
guess
.
The never type is useful with the panic!
macro as well. Recall the unwrap
function that we call on Option<T>
values to produce a value or panic with
this definition:
enum Option<T> {
Some(T),
None,
}
use crate::Option::*;
impl<T> Option<T> {
pub fn unwrap(self) -> T {
match self {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),
}
}
}
In this code, the same thing happens as in the match
in Listing 19-26: Rust
sees that val
has the type T
and panic!
has the type !
, so the result
of the overall match
expression is T
. This code works because panic!
doesn’t produce a value; it ends the program. In the None
case, we won’t be
returning a value from unwrap
, so this code is valid.
One final expression that has the type !
is a loop
:
fn main() {
print!("forever ");
loop {
print!("and ever ");
}
}
Here, the loop never ends, so !
is the value of the expression. However, this
wouldn’t be true if we included a break
, because the loop would terminate
when it got to the break
.
Dynamically Sized Types and the Sized
Trait
Rust needs to know certain details about its types, such as how much space to allocate for a value of a particular type. This leaves one corner of its type system a little confusing at first: the concept of dynamically sized types. Sometimes referred to as DSTs or unsized types, these types let us write code using values whose size we can know only at runtime.
Let’s dig into the details of a dynamically sized type called str
, which
we’ve been using throughout the book. That’s right, not &str
, but str
on
its own, is a DST. We can’t know how long the string is until runtime, meaning
we can’t create a variable of type str
, nor can we take an argument of type
str
. Consider the following code, which does not work:
fn main() {
let s1: str = "Hello there!";
let s2: str = "How's it going?";
}
Rust needs to know how much memory to allocate for any value of a particular
type, and all values of a type must use the same amount of memory. If Rust
allowed us to write this code, these two str
values would need to take up the
same amount of space. But they have different lengths: s1
needs 12 bytes of
storage and s2
needs 15. This is why it’s not possible to create a variable
holding a dynamically sized type.
So what do we do? In this case, you already know the answer: we make the types
of s1
and s2
a &str
rather than a str
. Recall from the “String
Slices” section of Chapter 4 that the slice data
structure just stores the starting position and the length of the slice. So
although a &T
is a single value that stores the memory address of where the
T
is located, a &str
is two values: the address of the str
and its
length. As such, we can know the size of a &str
value at compile time: it’s
twice the length of a usize
. That is, we always know the size of a &str
, no
matter how long the string it refers to is. In general, this is the way in
which dynamically sized types are used in Rust: they have an extra bit of
metadata that stores the size of the dynamic information. The golden rule of
dynamically sized types is that we must always put values of dynamically sized
types behind a pointer of some kind.
We can combine str
with all kinds of pointers: for example, Box<str>
or
Rc<str>
. In fact, you’ve seen this before but with a different dynamically
sized type: traits. Every trait is a dynamically sized type we can refer to by
using the name of the trait. In Chapter 17 in the “Using Trait Objects That
Allow for Values of Different
Types” section, we mentioned that to use traits as trait objects, we must
put them behind a pointer, such as &dyn Trait
or Box<dyn Trait>
(Rc<dyn Trait>
would work too).
To work with DSTs, Rust provides the Sized
trait to determine whether or not
a type’s size is known at compile time. This trait is automatically implemented
for everything whose size is known at compile time. In addition, Rust
implicitly adds a bound on Sized
to every generic function. That is, a
generic function definition like this:
fn generic<T>(t: T) {
// --snip--
}
is actually treated as though we had written this:
fn generic<T: Sized>(t: T) {
// --snip--
}
By default, generic functions will work only on types that have a known size at compile time. However, you can use the following special syntax to relax this restriction:
fn generic<T: ?Sized>(t: &T) {
// --snip--
}
A trait bound on ?Sized
means “T
may or may not be Sized
” and this
notation overrides the default that generic types must have a known size at
compile time. The ?Trait
syntax with this meaning is only available for
Sized
, not any other traits.
Also note that we switched the type of the t
parameter from T
to &T
.
Because the type might not be Sized
, we need to use it behind some kind of
pointer. In this case, we’ve chosen a reference.
Next, we’ll talk about functions and closures!
Advanced Functions and Closures
This section explores some advanced features related to functions and closures, including function pointers and returning closures.
Function Pointers
We’ve talked about how to pass closures to functions; you can also pass regular
functions to functions! This technique is useful when you want to pass a
function you’ve already defined rather than defining a new closure. Functions
coerce to the type fn
(with a lowercase f), not to be confused with the Fn
closure trait. The fn
type is called a function pointer. Passing functions
with function pointers will allow you to use functions as arguments to other
functions.
The syntax for specifying that a parameter is a function pointer is similar to
that of closures, as shown in Listing 19-27, where we’ve defined a function
add_one
that adds one to its parameter. The function do_twice
takes two
parameters: a function pointer to any function that takes an i32
parameter
and returns an i32
, and one i32
value. The do_twice
function calls the
function f
twice, passing it the arg
value, then adds the two function call
results together. The main
function calls do_twice
with the arguments
add_one
and 5
.
Filename: src/main.rs
fn add_one(x: i32) -> i32 { x + 1 } fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { f(arg) + f(arg) } fn main() { let answer = do_twice(add_one, 5); println!("The answer is: {}", answer); }
This code prints The answer is: 12
. We specify that the parameter f
in
do_twice
is an fn
that takes one parameter of type i32
and returns an
i32
. We can then call f
in the body of do_twice
. In main
, we can pass
the function name add_one
as the first argument to do_twice
.
Unlike closures, fn
is a type rather than a trait, so we specify fn
as the
parameter type directly rather than declaring a generic type parameter with one
of the Fn
traits as a trait bound.
Function pointers implement all three of the closure traits (Fn
, FnMut
, and
FnOnce
), meaning you can always pass a function pointer as an argument for a
function that expects a closure. It’s best to write functions using a generic
type and one of the closure traits so your functions can accept either
functions or closures.
That said, one example of where you would want to only accept fn
and not
closures is when interfacing with external code that doesn’t have closures: C
functions can accept functions as arguments, but C doesn’t have closures.
As an example of where you could use either a closure defined inline or a named
function, let’s look at a use of the map
method provided by the Iterator
trait in the standard library. To use the map
function to turn a vector of
numbers into a vector of strings, we could use a closure, like this:
fn main() { let list_of_numbers = vec![1, 2, 3]; let list_of_strings: Vec<String> = list_of_numbers.iter().map(|i| i.to_string()).collect(); }
Or we could name a function as the argument to map
instead of the closure,
like this:
fn main() { let list_of_numbers = vec![1, 2, 3]; let list_of_strings: Vec<String> = list_of_numbers.iter().map(ToString::to_string).collect(); }
Note that we must use the fully qualified syntax that we talked about earlier
in the “Advanced Traits” section because
there are multiple functions available named to_string
. Here, we’re using the
to_string
function defined in the ToString
trait, which the standard
library has implemented for any type that implements Display
.
Recall from the “Enum values” section of Chapter 6 that the name of each enum variant that we define also becomes an initializer function. We can use these initializer functions as function pointers that implement the closure traits, which means we can specify the initializer functions as arguments for methods that take closures, like so:
fn main() { enum Status { Value(u32), Stop, } let list_of_statuses: Vec<Status> = (0u32..20).map(Status::Value).collect(); }
Here we create Status::Value
instances using each u32
value in the range
that map
is called on by using the initializer function of Status::Value
.
Some people prefer this style, and some people prefer to use closures. They
compile to the same code, so use whichever style is clearer to you.
Returning Closures
Closures are represented by traits, which means you can’t return closures
directly. In most cases where you might want to return a trait, you can instead
use the concrete type that implements the trait as the return value of the
function. However, you can’t do that with closures because they don’t have a
concrete type that is returnable; you’re not allowed to use the function
pointer fn
as a return type, for example.
The following code tries to return a closure directly, but it won’t compile:
fn returns_closure() -> dyn Fn(i32) -> i32 {
|x| x + 1
}
The compiler error is as follows:
$ cargo build
Compiling functions-example v0.1.0 (file:///projects/functions-example)
error[E0746]: return type cannot have an unboxed trait object
--> src/lib.rs:1:25
|
1 | fn returns_closure() -> dyn Fn(i32) -> i32 {
| ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= note: for information on `impl Trait`, see <https://doc.rust-lang.org/book/ch10-02-traits.html#returning-types-that-implement-traits>
help: use `impl Fn(i32) -> i32` as the return type, as all return paths are of type `[closure@src/lib.rs:2:5: 2:8]`, which implements `Fn(i32) -> i32`
|
1 | fn returns_closure() -> impl Fn(i32) -> i32 {
| ~~~~~~~~~~~~~~~~~~~
For more information about this error, try `rustc --explain E0746`.
error: could not compile `functions-example` due to previous error
The error references the Sized
trait again! Rust doesn’t know how much space
it will need to store the closure. We saw a solution to this problem earlier.
We can use a trait object:
fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
Box::new(|x| x + 1)
}
This code will compile just fine. For more about trait objects, refer to the section “Using Trait Objects That Allow for Values of Different Types” in Chapter 17.
Next, let’s look at macros!
Macros
We’ve used macros like println!
throughout this book, but we haven’t fully
explored what a macro is and how it works. The term macro refers to a family
of features in Rust: declarative macros with macro_rules!
and three kinds
of procedural macros:
- Custom
#[derive]
macros that specify code added with thederive
attribute used on structs and enums - Attribute-like macros that define custom attributes usable on any item
- Function-like macros that look like function calls but operate on the tokens specified as their argument
We’ll talk about each of these in turn, but first, let’s look at why we even need macros when we already have functions.
The Difference Between Macros and Functions
Fundamentally, macros are a way of writing code that writes other code, which
is known as metaprogramming. In Appendix C, we discuss the derive
attribute, which generates an implementation of various traits for you. We’ve
also used the println!
and vec!
macros throughout the book. All of these
macros expand to produce more code than the code you’ve written manually.
Metaprogramming is useful for reducing the amount of code you have to write and maintain, which is also one of the roles of functions. However, macros have some additional powers that functions don’t.
A function signature must declare the number and type of parameters the
function has. Macros, on the other hand, can take a variable number of
parameters: we can call println!("hello")
with one argument or
println!("hello {}", name)
with two arguments. Also, macros are expanded
before the compiler interprets the meaning of the code, so a macro can, for
example, implement a trait on a given type. A function can’t, because it gets
called at runtime and a trait needs to be implemented at compile time.
The downside to implementing a macro instead of a function is that macro definitions are more complex than function definitions because you’re writing Rust code that writes Rust code. Due to this indirection, macro definitions are generally more difficult to read, understand, and maintain than function definitions.
Another important difference between macros and functions is that you must define macros or bring them into scope before you call them in a file, as opposed to functions you can define anywhere and call anywhere.
Declarative Macros with macro_rules!
for General Metaprogramming
The most widely used form of macros in Rust is the declarative macro. These
are also sometimes referred to as “macros by example,” “macro_rules!
macros,”
or just plain “macros.” At their core, declarative macros allow you to write
something similar to a Rust match
expression. As discussed in Chapter 6,
match
expressions are control structures that take an expression, compare the
resulting value of the expression to patterns, and then run the code associated
with the matching pattern. Macros also compare a value to patterns that are
associated with particular code: in this situation, the value is the literal
Rust source code passed to the macro; the patterns are compared with the
structure of that source code; and the code associated with each pattern, when
matched, replaces the code passed to the macro. This all happens during
compilation.
To define a macro, you use the macro_rules!
construct. Let’s explore how to
use macro_rules!
by looking at how the vec!
macro is defined. Chapter 8
covered how we can use the vec!
macro to create a new vector with particular
values. For example, the following macro creates a new vector containing three
integers:
#![allow(unused)] fn main() { let v: Vec<u32> = vec![1, 2, 3]; }
We could also use the vec!
macro to make a vector of two integers or a vector
of five string slices. We wouldn’t be able to use a function to do the same
because we wouldn’t know the number or type of values up front.
Listing 19-28 shows a slightly simplified definition of the vec!
macro.
Filename: src/lib.rs
#[macro_export]
macro_rules! vec {
( $( $x:expr ),* ) => {
{
let mut temp_vec = Vec::new();
$(
temp_vec.push($x);
)*
temp_vec
}
};
}
Note: The actual definition of the
vec!
macro in the standard library includes code to preallocate the correct amount of memory up front. That code is an optimization that we don’t include here to make the example simpler.
The #[macro_export]
annotation indicates that this macro should be made
available whenever the crate in which the macro is defined is brought into
scope. Without this annotation, the macro can’t be brought into scope.
We then start the macro definition with macro_rules!
and the name of the
macro we’re defining without the exclamation mark. The name, in this case
vec
, is followed by curly brackets denoting the body of the macro definition.
The structure in the vec!
body is similar to the structure of a match
expression. Here we have one arm with the pattern ( $( $x:expr ),* )
,
followed by =>
and the block of code associated with this pattern. If the
pattern matches, the associated block of code will be emitted. Given that this
is the only pattern in this macro, there is only one valid way to match; any
other pattern will result in an error. More complex macros will have more than
one arm.
Valid pattern syntax in macro definitions is different than the pattern syntax covered in Chapter 18 because macro patterns are matched against Rust code structure rather than values. Let’s walk through what the pattern pieces in Listing 19-28 mean; for the full macro pattern syntax, see the Rust Reference.
First, we use a set of parentheses to encompass the whole pattern. We use a
dollar sign ($
) to declare a variable in the macro system that will contain
the Rust code matching the pattern. The dollar sign makes it clear this is a
macro variable as opposed to a regular Rust variable. Next comes a set of
parentheses that captures values that match the pattern within the parentheses
for use in the replacement code. Within $()
is $x:expr
, which matches any
Rust expression and gives the expression the name $x
.
The comma following $()
indicates that a literal comma separator character
could optionally appear after the code that matches the code in $()
. The *
specifies that the pattern matches zero or more of whatever precedes the *
.
When we call this macro with vec![1, 2, 3];
, the $x
pattern matches three
times with the three expressions 1
, 2
, and 3
.
Now let’s look at the pattern in the body of the code associated with this arm:
temp_vec.push()
within $()*
is generated for each part that matches $()
in the pattern zero or more times depending on how many times the pattern
matches. The $x
is replaced with each expression matched. When we call this
macro with vec![1, 2, 3];
, the code generated that replaces this macro call
will be the following:
{
let mut temp_vec = Vec::new();
temp_vec.push(1);
temp_vec.push(2);
temp_vec.push(3);
temp_vec
}
We’ve defined a macro that can take any number of arguments of any type and can generate code to create a vector containing the specified elements.
To learn more about how to write macros, consult the online documentation or other resources, such as “The Little Book of Rust Macros” started by Daniel Keep and continued by Lukas Wirth.
Procedural Macros for Generating Code from Attributes
The second form of macros is the procedural macro, which acts more like a function (and is a type of procedure). Procedural macros accept some code as an input, operate on that code, and produce some code as an output rather than matching against patterns and replacing the code with other code as declarative macros do. The three kinds of procedural macros are custom derive, attribute-like, and function-like, and all work in a similar fashion.
When creating procedural macros, the definitions must reside in their own crate
with a special crate type. This is for complex technical reasons that we hope
to eliminate in the future. In Listing 19-29, we show how to define a
procedural macro, where some_attribute
is a placeholder for using a specific
macro variety.
Filename: src/lib.rs
use proc_macro;
#[some_attribute]
pub fn some_name(input: TokenStream) -> TokenStream {
}
The function that defines a procedural macro takes a TokenStream
as an input
and produces a TokenStream
as an output. The TokenStream
type is defined by
the proc_macro
crate that is included with Rust and represents a sequence of
tokens. This is the core of the macro: the source code that the macro is
operating on makes up the input TokenStream
, and the code the macro produces
is the output TokenStream
. The function also has an attribute attached to it
that specifies which kind of procedural macro we’re creating. We can have
multiple kinds of procedural macros in the same crate.
Let’s look at the different kinds of procedural macros. We’ll start with a custom derive macro and then explain the small dissimilarities that make the other forms different.
How to Write a Custom derive
Macro
Let’s create a crate named hello_macro
that defines a trait named
HelloMacro
with one associated function named hello_macro
. Rather than
making our users implement the HelloMacro
trait for each of their types,
we’ll provide a procedural macro so users can annotate their type with
#[derive(HelloMacro)]
to get a default implementation of the hello_macro
function. The default implementation will print Hello, Macro! My name is TypeName!
where TypeName
is the name of the type on which this trait has
been defined. In other words, we’ll write a crate that enables another
programmer to write code like Listing 19-30 using our crate.
Filename: src/main.rs
use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;
#[derive(HelloMacro)]
struct Pancakes;
fn main() {
Pancakes::hello_macro();
}
This code will print Hello, Macro! My name is Pancakes!
when we’re done. The
first step is to make a new library crate, like this:
$ cargo new hello_macro --lib
Next, we’ll define the HelloMacro
trait and its associated function:
Filename: src/lib.rs
pub trait HelloMacro {
fn hello_macro();
}
We have a trait and its function. At this point, our crate user could implement the trait to achieve the desired functionality, like so:
use hello_macro::HelloMacro;
struct Pancakes;
impl HelloMacro for Pancakes {
fn hello_macro() {
println!("Hello, Macro! My name is Pancakes!");
}
}
fn main() {
Pancakes::hello_macro();
}
However, they would need to write the implementation block for each type they
wanted to use with hello_macro
; we want to spare them from having to do this
work.
Additionally, we can’t yet provide the hello_macro
function with default
implementation that will print the name of the type the trait is implemented
on: Rust doesn’t have reflection capabilities, so it can’t look up the type’s
name at runtime. We need a macro to generate code at compile time.
The next step is to define the procedural macro. At the time of this writing,
procedural macros need to be in their own crate. Eventually, this restriction
might be lifted. The convention for structuring crates and macro crates is as
follows: for a crate named foo
, a custom derive procedural macro crate is
called foo_derive
. Let’s start a new crate called hello_macro_derive
inside
our hello_macro
project:
$ cargo new hello_macro_derive --lib
Our two crates are tightly related, so we create the procedural macro crate
within the directory of our hello_macro
crate. If we change the trait
definition in hello_macro
, we’ll have to change the implementation of the
procedural macro in hello_macro_derive
as well. The two crates will need to
be published separately, and programmers using these crates will need to add
both as dependencies and bring them both into scope. We could instead have the
hello_macro
crate use hello_macro_derive
as a dependency and re-export the
procedural macro code. However, the way we’ve structured the project makes it
possible for programmers to use hello_macro
even if they don’t want the
derive
functionality.
We need to declare the hello_macro_derive
crate as a procedural macro crate.
We’ll also need functionality from the syn
and quote
crates, as you’ll see
in a moment, so we need to add them as dependencies. Add the following to the
Cargo.toml file for hello_macro_derive
:
Filename: hello_macro_derive/Cargo.toml
[lib]
proc-macro = true
[dependencies]
syn = "1.0"
quote = "1.0"
To start defining the procedural macro, place the code in Listing 19-31 into
your src/lib.rs file for the hello_macro_derive
crate. Note that this code
won’t compile until we add a definition for the impl_hello_macro
function.
Filename: hello_macro_derive/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_hello_macro(&ast)
}
Notice that we’ve split the code into the hello_macro_derive
function, which
is responsible for parsing the TokenStream
, and the impl_hello_macro
function, which is responsible for transforming the syntax tree: this makes
writing a procedural macro more convenient. The code in the outer function
(hello_macro_derive
in this case) will be the same for almost every
procedural macro crate you see or create. The code you specify in the body of
the inner function (impl_hello_macro
in this case) will be different
depending on your procedural macro’s purpose.
We’ve introduced three new crates: proc_macro
, syn
, and quote
. The
proc_macro
crate comes with Rust, so we didn’t need to add that to the
dependencies in Cargo.toml. The proc_macro
crate is the compiler’s API that
allows us to read and manipulate Rust code from our code.
The syn
crate parses Rust code from a string into a data structure that we
can perform operations on. The quote
crate turns syn
data structures back
into Rust code. These crates make it much simpler to parse any sort of Rust
code we might want to handle: writing a full parser for Rust code is no simple
task.
The hello_macro_derive
function will be called when a user of our library
specifies #[derive(HelloMacro)]
on a type. This is possible because we’ve
annotated the hello_macro_derive
function here with proc_macro_derive
and
specified the name HelloMacro
, which matches our trait name; this is the
convention most procedural macros follow.
The hello_macro_derive
function first converts the input
from a
TokenStream
to a data structure that we can then interpret and perform
operations on. This is where syn
comes into play. The parse
function in
syn
takes a TokenStream
and returns a DeriveInput
struct representing the
parsed Rust code. Listing 19-32 shows the relevant parts of the DeriveInput
struct we get from parsing the struct Pancakes;
string:
DeriveInput {
// --snip--
ident: Ident {
ident: "Pancakes",
span: #0 bytes(95..103)
},
data: Struct(
DataStruct {
struct_token: Struct,
fields: Unit,
semi_token: Some(
Semi
)
}
)
}
The fields of this struct show that the Rust code we’ve parsed is a unit struct
with the ident
(identifier, meaning the name) of Pancakes
. There are more
fields on this struct for describing all sorts of Rust code; check the syn
documentation for DeriveInput
for more information.
Soon we’ll define the impl_hello_macro
function, which is where we’ll build
the new Rust code we want to include. But before we do, note that the output
for our derive macro is also a TokenStream
. The returned TokenStream
is
added to the code that our crate users write, so when they compile their crate,
they’ll get the extra functionality that we provide in the modified
TokenStream
.
You might have noticed that we’re calling unwrap
to cause the
hello_macro_derive
function to panic if the call to the syn::parse
function
fails here. It’s necessary for our procedural macro to panic on errors because
proc_macro_derive
functions must return TokenStream
rather than Result
to
conform to the procedural macro API. We’ve simplified this example by using
unwrap
; in production code, you should provide more specific error messages
about what went wrong by using panic!
or expect
.
Now that we have the code to turn the annotated Rust code from a TokenStream
into a DeriveInput
instance, let’s generate the code that implements the
HelloMacro
trait on the annotated type, as shown in Listing 19-33.
Filename: hello_macro_derive/src/lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn;
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// Construct a representation of Rust code as a syntax tree
// that we can manipulate
let ast = syn::parse(input).unwrap();
// Build the trait implementation
impl_hello_macro(&ast)
}
fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream {
let name = &ast.ident;
let gen = quote! {
impl HelloMacro for #name {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", stringify!(#name));
}
}
};
gen.into()
}
We get an Ident
struct instance containing the name (identifier) of the
annotated type using ast.ident
. The struct in Listing 19-32 shows that when
we run the impl_hello_macro
function on the code in Listing 19-30, the
ident
we get will have the ident
field with a value of "Pancakes"
. Thus,
the name
variable in Listing 19-33 will contain an Ident
struct instance
that, when printed, will be the string "Pancakes"
, the name of the struct in
Listing 19-30.
The quote!
macro lets us define the Rust code that we want to return. The
compiler expects something different to the direct result of the quote!
macro’s execution, so we need to convert it to a TokenStream
. We do this by
calling the into
method, which consumes this intermediate representation and
returns a value of the required TokenStream
type.
The quote!
macro also provides some very cool templating mechanics: we can
enter #name
, and quote!
will replace it with the value in the variable
name
. You can even do some repetition similar to the way regular macros work.
Check out the quote
crate’s docs for a thorough introduction.
We want our procedural macro to generate an implementation of our HelloMacro
trait for the type the user annotated, which we can get by using #name
. The
trait implementation has the one function hello_macro
, whose body contains the
functionality we want to provide: printing Hello, Macro! My name is
and then
the name of the annotated type.
The stringify!
macro used here is built into Rust. It takes a Rust
expression, such as 1 + 2
, and at compile time turns the expression into a
string literal, such as "1 + 2"
. This is different than format!
or
println!
, macros which evaluate the expression and then turn the result into
a String
. There is a possibility that the #name
input might be an
expression to print literally, so we use stringify!
. Using stringify!
also
saves an allocation by converting #name
to a string literal at compile time.
At this point, cargo build
should complete successfully in both hello_macro
and hello_macro_derive
. Let’s hook up these crates to the code in Listing
19-30 to see the procedural macro in action! Create a new binary project in
your projects directory using cargo new pancakes
. We need to add
hello_macro
and hello_macro_derive
as dependencies in the pancakes
crate’s Cargo.toml. If you’re publishing your versions of hello_macro
and
hello_macro_derive
to crates.io, they would be regular
dependencies; if not, you can specify them as path
dependencies as follows:
hello_macro = { path = "../hello_macro" }
hello_macro_derive = { path = "../hello_macro/hello_macro_derive" }
Put the code in Listing 19-30 into src/main.rs, and run cargo run
: it
should print Hello, Macro! My name is Pancakes!
The implementation of the
HelloMacro
trait from the procedural macro was included without the
pancakes
crate needing to implement it; the #[derive(HelloMacro)]
added the
trait implementation.
Next, let’s explore how the other kinds of procedural macros differ from custom derive macros.
Attribute-like macros
Attribute-like macros are similar to custom derive macros, but instead of
generating code for the derive
attribute, they allow you to create new
attributes. They’re also more flexible: derive
only works for structs and
enums; attributes can be applied to other items as well, such as functions.
Here’s an example of using an attribute-like macro: say you have an attribute
named route
that annotates functions when using a web application framework:
#[route(GET, "/")]
fn index() {
This #[route]
attribute would be defined by the framework as a procedural
macro. The signature of the macro definition function would look like this:
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream {
Here, we have two parameters of type TokenStream
. The first is for the
contents of the attribute: the GET, "/"
part. The second is the body of the
item the attribute is attached to: in this case, fn index() {}
and the rest
of the function’s body.
Other than that, attribute-like macros work the same way as custom derive
macros: you create a crate with the proc-macro
crate type and implement a
function that generates the code you want!
Function-like macros
Function-like macros define macros that look like function calls. Similarly to
macro_rules!
macros, they’re more flexible than functions; for example, they
can take an unknown number of arguments. However, macro_rules!
macros can be
defined only using the match-like syntax we discussed in the section
“Declarative Macros with macro_rules!
for General
Metaprogramming” earlier. Function-like macros take a
TokenStream
parameter and their definition manipulates that TokenStream
using Rust code as the other two types of procedural macros do. An example of a
function-like macro is an sql!
macro that might be called like so:
let sql = sql!(SELECT * FROM posts WHERE id=1);
This macro would parse the SQL statement inside it and check that it’s
syntactically correct, which is much more complex processing than a
macro_rules!
macro can do. The sql!
macro would be defined like this:
#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
This definition is similar to the custom derive macro’s signature: we receive the tokens that are inside the parentheses and return the code we wanted to generate.
Summary
Whew! Now you have some Rust features in your toolbox that you likely won’t use often, but you’ll know they’re available in very particular circumstances. We’ve introduced several complex topics so that when you encounter them in error message suggestions or in other peoples’ code, you’ll be able to recognize these concepts and syntax. Use this chapter as a reference to guide you to solutions.
Next, we’ll put everything we’ve discussed throughout the book into practice and do one more project!
Final Project: Building a Multithreaded Web Server
It’s been a long journey, but we’ve reached the end of the book. In this chapter, we’ll build one more project together to demonstrate some of the concepts we covered in the final chapters, as well as recap some earlier lessons.
For our final project, we’ll make a web server that says “hello” and looks like Figure 20-1 in a web browser.
Here is our plan for building the web server:
- Learn a bit about TCP and HTTP.
- Listen for TCP connections on a socket.
- Parse a small number of HTTP requests.
- Create a proper HTTP response.
- Improve the throughput of our server with a thread pool.
Before we get started, we should mention one detail: the method we’ll use won’t be the best way to build a web server with Rust. Community members have published a number of production-ready crates available on crates.io that provide more complete web server and thread pool implementations than we’ll build. However, our intention in this chapter is to help you learn, not to take the easy route. Because Rust is a systems programming language, we can choose the level of abstraction we want to work with and can go to a lower level than is possible or practical in other languages. We’ll therefore write the basic HTTP server and thread pool manually so you can learn the general ideas and techniques behind the crates you might use in the future.
Building a Single-Threaded Web Server
We’ll start by getting a single-threaded web server working. Before we begin, let’s look at a quick overview of the protocols involved in building web servers. The details of these protocols are beyond the scope of this book, but a brief overview will give you the information you need.
The two main protocols involved in web servers are Hypertext Transfer Protocol (HTTP) and Transmission Control Protocol (TCP). Both protocols are request-response protocols, meaning a client initiates requests and a server listens to the requests and provides a response to the client. The contents of those requests and responses are defined by the protocols.
TCP is the lower-level protocol that describes the details of how information gets from one server to another but doesn’t specify what that information is. HTTP builds on top of TCP by defining the contents of the requests and responses. It’s technically possible to use HTTP with other protocols, but in the vast majority of cases, HTTP sends its data over TCP. We’ll work with the raw bytes of TCP and HTTP requests and responses.
Listening to the TCP Connection
Our web server needs to listen to a TCP connection, so that’s the first part
we’ll work on. The standard library offers a std::net
module that lets us do
this. Let’s make a new project in the usual fashion:
$ cargo new hello
Created binary (application) `hello` project
$ cd hello
Now enter the code in Listing 20-1 in src/main.rs to start. This code will
listen at the local address 127.0.0.1:7878
for incoming TCP streams. When it
gets an incoming stream, it will print Connection established!
.
Filename: src/main.rs
use std::net::TcpListener; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); println!("Connection established!"); } }
Using TcpListener
, we can listen for TCP connections at the address
127.0.0.1:7878
. In the address, the section before the colon is an IP address
representing your computer (this is the same on every computer and doesn’t
represent the authors’ computer specifically), and 7878
is the port. We’ve
chosen this port for two reasons: HTTP isn’t normally accepted on this port so
our server is unlikely to conflict with any other web server you might have
running on your machine, and 7878 is rust typed on a telephone.
The bind
function in this scenario works like the new
function in that it
will return a new TcpListener
instance. The function is called bind
because, in networking, connecting to a port to listen to is known as “binding
to a port.”
The bind
function returns a Result<T, E>
, which indicates that it’s
possible for binding to fail. For example, connecting to port 80 requires
administrator privileges (nonadministrators can listen only on ports higher
than 1023), so if we tried to connect to port 80 without being an
administrator, binding wouldn’t work. Binding also wouldn’t work, for example,
if we ran two instances of our program and so had two programs listening to the
same port. Because we’re writing a basic server just for learning purposes, we
won’t worry about handling these kinds of errors; instead, we use unwrap
to
stop the program if errors happen.
The incoming
method on TcpListener
returns an iterator that gives us a
sequence of streams (more specifically, streams of type TcpStream
). A single
stream represents an open connection between the client and the server. A
connection is the name for the full request and response process in which a
client connects to the server, the server generates a response, and the server
closes the connection. As such, we will read from the TcpStream
to see what
the client sent and then write our response to the stream to send data back to
the client. Overall, this for
loop will process each connection in turn and
produce a series of streams for us to handle.
For now, our handling of the stream consists of calling unwrap
to terminate
our program if the stream has any errors; if there aren’t any errors, the
program prints a message. We’ll add more functionality for the success case in
the next listing. The reason we might receive errors from the incoming
method
when a client connects to the server is that we’re not actually iterating over
connections. Instead, we’re iterating over connection attempts. The
connection might not be successful for a number of reasons, many of them
operating system specific. For example, many operating systems have a limit to
the number of simultaneous open connections they can support; new connection
attempts beyond that number will produce an error until some of the open
connections are closed.
Let’s try running this code! Invoke cargo run
in the terminal and then load
127.0.0.1:7878 in a web browser. The browser should show an error message
like “Connection reset,” because the server isn’t currently sending back any
data. But when you look at your terminal, you should see several messages that
were printed when the browser connected to the server!
Running `target/debug/hello`
Connection established!
Connection established!
Connection established!
Sometimes, you’ll see multiple messages printed for one browser request; the reason might be that the browser is making a request for the page as well as a request for other resources, like the favicon.ico icon that appears in the browser tab.
It could also be that the browser is trying to connect to the server multiple
times because the server isn’t responding with any data. When stream
goes out
of scope and is dropped at the end of the loop, the connection is closed as
part of the drop
implementation. Browsers sometimes deal with closed
connections by retrying, because the problem might be temporary. The important
factor is that we’ve successfully gotten a handle to a TCP connection!
Remember to stop the program by pressing ctrl-c
when you’re done running a particular version of the code. Then restart the
program by invoking the cargo run
command after you’ve made each set of code
changes to make sure you’re running the newest code.
Reading the Request
Let’s implement the functionality to read the request from the browser! To
separate the concerns of first getting a connection and then taking some action
with the connection, we’ll start a new function for processing connections. In
this new handle_connection
function, we’ll read data from the TCP stream and
print it so we can see the data being sent from the browser. Change the code to
look like Listing 20-2.
Filename: src/main.rs
use std::{ io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); println!("Request: {:#?}", http_request); }
We bring std::io::prelude
and std::io::BufReader
into scope to get access
to traits and types that let us read from and write to the stream. In the for
loop in the main
function, instead of printing a message that says we made a
connection, we now call the new handle_connection
function and pass the
stream
to it.
In the handle_connection
function, we create a new BufReader
instance that
wraps a mutable reference to the stream
. BufReader
adds buffering by
managing calls to the std::io::Read
trait methods for us.
We create a variable named http_request
to collect the lines of the request
the browser sends to our server. We indicate that we want to collect these
lines in a vector by adding the Vec<_>
type annotation.
BufReader
implements the std::io::BufRead
trait, which provides the lines
method. The lines
method returns an iterator of Result<String, std::io::Error>
by splitting the stream of data whenever it sees a newline
byte. To get each String
, we map and unwrap
each Result
. The Result
might be an error if the data isn’t valid UTF-8 or if there was a problem
reading from the stream. Again, a production program should handle these errors
more gracefully, but we’re choosing to stop the program in the error case for
simplicity.
The browser signals the end of an HTTP request by sending two newline characters in a row, so to get one request from the stream, we take lines until we get a line that is the empty string. Once we’ve collected the lines into the vector, we’re printing them out using pretty debug formatting so we can take a look at the instructions the web browser is sending to our server.
Let’s try this code! Start the program and make a request in a web browser again. Note that we’ll still get an error page in the browser, but our program’s output in the terminal will now look similar to this:
$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/hello`
Request: [
"GET / HTTP/1.1",
"Host: 127.0.0.1:7878",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:99.0) Gecko/20100101 Firefox/99.0",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language: en-US,en;q=0.5",
"Accept-Encoding: gzip, deflate, br",
"DNT: 1",
"Connection: keep-alive",
"Upgrade-Insecure-Requests: 1",
"Sec-Fetch-Dest: document",
"Sec-Fetch-Mode: navigate",
"Sec-Fetch-Site: none",
"Sec-Fetch-User: ?1",
"Cache-Control: max-age=0",
]
Depending on your browser, you might get slightly different output. Now that
we’re printing the request data, we can see why we get multiple connections
from one browser request by looking at the path after GET
in the first line
of the request. If the repeated connections are all requesting /, we know the
browser is trying to fetch / repeatedly because it’s not getting a response
from our program.
Let’s break down this request data to understand what the browser is asking of our program.
A Closer Look at an HTTP Request
HTTP is a text-based protocol, and a request takes this format:
Method Request-URI HTTP-Version CRLF
headers CRLF
message-body
The first line is the request line that holds information about what the
client is requesting. The first part of the request line indicates the method
being used, such as GET
or POST
, which describes how the client is making
this request. Our client used a GET
request, which means it is asking for
information.
The next part of the request line is /, which indicates the Uniform Resource Identifier (URI) the client is requesting: a URI is almost, but not quite, the same as a Uniform Resource Locator (URL). The difference between URIs and URLs isn’t important for our purposes in this chapter, but the HTTP spec uses the term URI, so we can just mentally substitute URL for URI here.
The last part is the HTTP version the client uses, and then the request line
ends in a CRLF sequence. (CRLF stands for carriage return and line feed,
which are terms from the typewriter days!) The CRLF sequence can also be
written as \r\n
, where \r
is a carriage return and \n
is a line feed. The
CRLF sequence separates the request line from the rest of the request data.
Note that when the CRLF is printed, we see a new line start rather than \r\n
.
Looking at the request line data we received from running our program so far,
we see that GET
is the method, / is the request URI, and HTTP/1.1
is the
version.
After the request line, the remaining lines starting from Host:
onward are
headers. GET
requests have no body.
Try making a request from a different browser or asking for a different address, such as 127.0.0.1:7878/test, to see how the request data changes.
Now that we know what the browser is asking for, let’s send back some data!
Writing a Response
We’re going to implement sending data in response to a client request. Responses have the following format:
HTTP-Version Status-Code Reason-Phrase CRLF
headers CRLF
message-body
The first line is a status line that contains the HTTP version used in the response, a numeric status code that summarizes the result of the request, and a reason phrase that provides a text description of the status code. After the CRLF sequence are any headers, another CRLF sequence, and the body of the response.
Here is an example response that uses HTTP version 1.1, has a status code of 200, an OK reason phrase, no headers, and no body:
HTTP/1.1 200 OK\r\n\r\n
The status code 200 is the standard success response. The text is a tiny
successful HTTP response. Let’s write this to the stream as our response to a
successful request! From the handle_connection
function, remove the
println!
that was printing the request data and replace it with the code in
Listing 20-3.
Filename: src/main.rs
use std::{ io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); let response = "HTTP/1.1 200 OK\r\n\r\n"; stream.write_all(response.as_bytes()).unwrap(); }
The first new line defines the response
variable that holds the success
message’s data. Then we call as_bytes
on our response
to convert the string
data to bytes. The write_all
method on stream
takes a &[u8]
and sends
those bytes directly down the connection. Because the write_all
operation
could fail, we use unwrap
on any error result as before. Again, in a real
application you would add error handling here.
With these changes, let’s run our code and make a request. We’re no longer printing any data to the terminal, so we won’t see any output other than the output from Cargo. When you load 127.0.0.1:7878 in a web browser, you should get a blank page instead of an error. You’ve just hand-coded receiving an HTTP request and sending a response!
Returning Real HTML
Let’s implement the functionality for returning more than a blank page. Create the new file hello.html in the root of your project directory, not in the src directory. You can input any HTML you want; Listing 20-4 shows one possibility.
Filename: hello.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Hello!</h1>
<p>Hi from Rust</p>
</body>
</html>
This is a minimal HTML5 document with a heading and some text. To return this
from the server when a request is received, we’ll modify handle_connection
as
shown in Listing 20-5 to read the HTML file, add it to the response as a body,
and send it.
Filename: src/main.rs
use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; // --snip-- fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let http_request: Vec<_> = buf_reader .lines() .map(|result| result.unwrap()) .take_while(|line| !line.is_empty()) .collect(); let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); }
We’ve added fs
to the use
statement to bring the standard library’s
filesystem module into scope. The code for reading the contents of a file to a
string should look familiar; we used it in Chapter 12 when we read the contents
of a file for our I/O project in Listing 12-4.
Next, we use format!
to add the file’s contents as the body of the success
response. To ensure a valid HTTP response, we add the Content-Length
header
which is set to the size of our response body, in this case the size of
hello.html
.
Run this code with cargo run
and load 127.0.0.1:7878 in your browser; you
should see your HTML rendered!
Currently, we’re ignoring the request data in http_request
and just sending
back the contents of the HTML file unconditionally. That means if you try
requesting 127.0.0.1:7878/something-else in your browser, you’ll still get
back this same HTML response. At the moment, our server is very limited and
does not do what most web servers do. We want to customize our responses
depending on the request and only send back the HTML file for a well-formed
request to /.
Validating the Request and Selectively Responding
Right now, our web server will return the HTML in the file no matter what the
client requested. Let’s add functionality to check that the browser is
requesting / before returning the HTML file and return an error if the
browser requests anything else. For this we need to modify handle_connection
,
as shown in Listing 20-6. This new code checks the content of the request
received against what we know a request for / looks like and adds if
and
else
blocks to treat requests differently.
Filename: src/main.rs
use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } // --snip-- fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); if request_line == "GET / HTTP/1.1" { let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); } else { // some other request } }
We’re only going to be looking at the first line of the HTTP request, so rather
than reading the entire request into a vector, we’re calling next
to get the
first item from the iterator. The first unwrap
takes care of the Option
and
stops the program if the iterator has no items. The second unwrap
handles the
Result
and has the same effect as the unwrap
that was in the map
added in
Listing 20-2.
Next, we check the request_line
to see if it equals the request line of a GET
request to the / path. If it does, the if
block returns the contents of our
HTML file.
If the request_line
does not equal the GET request to the / path, it
means we’ve received some other request. We’ll add code to the else
block in
a moment to respond to all other requests.
Run this code now and request 127.0.0.1:7878; you should get the HTML in hello.html. If you make any other request, such as 127.0.0.1:7878/something-else, you’ll get a connection error like those you saw when running the code in Listing 20-1 and Listing 20-2.
Now let’s add the code in Listing 20-7 to the else
block to return a response
with the status code 404, which signals that the content for the request was
not found. We’ll also return some HTML for a page to render in the browser
indicating the response to the end user.
Filename: src/main.rs
use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); if request_line == "GET / HTTP/1.1" { let status_line = "HTTP/1.1 200 OK"; let contents = fs::read_to_string("hello.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); // --snip-- } else { let status_line = "HTTP/1.1 404 NOT FOUND"; let contents = fs::read_to_string("404.html").unwrap(); let length = contents.len(); let response = format!( "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" ); stream.write_all(response.as_bytes()).unwrap(); } }
Here, our response has a status line with status code 404 and the reason phrase
NOT FOUND
. The body of the response will be the HTML in the file 404.html.
You’ll need to create a 404.html file next to hello.html for the error
page; again feel free to use any HTML you want or use the example HTML in
Listing 20-8.
Filename: 404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Oops!</h1>
<p>Sorry, I don't know what you're asking for.</p>
</body>
</html>
With these changes, run your server again. Requesting 127.0.0.1:7878 should return the contents of hello.html, and any other request, like 127.0.0.1:7878/foo, should return the error HTML from 404.html.
A Touch of Refactoring
At the moment the if
and else
blocks have a lot of repetition: they’re both
reading files and writing the contents of the files to the stream. The only
differences are the status line and the filename. Let’s make the code more
concise by pulling out those differences into separate if
and else
lines
that will assign the values of the status line and the filename to variables;
we can then use those variables unconditionally in the code to read the file
and write the response. Listing 20-9 shows the resulting code after replacing
the large if
and else
blocks.
Filename: src/main.rs
use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } // --snip-- fn handle_connection(mut stream: TcpStream) { // --snip-- let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = if request_line == "GET / HTTP/1.1" { ("HTTP/1.1 200 OK", "hello.html") } else { ("HTTP/1.1 404 NOT FOUND", "404.html") }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); }
Now the if
and else
blocks only return the appropriate values for the
status line and filename in a tuple; we then use destructuring to assign these
two values to status_line
and filename
using a pattern in the let
statement, as discussed in Chapter 18.
The previously duplicated code is now outside the if
and else
blocks and
uses the status_line
and filename
variables. This makes it easier to see
the difference between the two cases, and it means we have only one place to
update the code if we want to change how the file reading and response writing
work. The behavior of the code in Listing 20-9 will be the same as that in
Listing 20-8.
Awesome! We now have a simple web server in approximately 40 lines of Rust code that responds to one request with a page of content and responds to all other requests with a 404 response.
Currently, our server runs in a single thread, meaning it can only serve one request at a time. Let’s examine how that can be a problem by simulating some slow requests. Then we’ll fix it so our server can handle multiple requests at once.
Turning Our Single-Threaded Server into a Multithreaded Server
Right now, the server will process each request in turn, meaning it won’t process a second connection until the first is finished processing. If the server received more and more requests, this serial execution would be less and less optimal. If the server receives a request that takes a long time to process, subsequent requests will have to wait until the long request is finished, even if the new requests can be processed quickly. We’ll need to fix this, but first, we’ll look at the problem in action.
Simulating a Slow Request in the Current Server Implementation
We’ll look at how a slow-processing request can affect other requests made to our current server implementation. Listing 20-10 implements handling a request to /sleep with a simulated slow response that will cause the server to sleep for 5 seconds before responding.
Filename: src/main.rs
use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, thread, time::Duration, }; // --snip-- fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); handle_connection(stream); } } fn handle_connection(mut stream: TcpStream) { // --snip-- let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; // --snip-- let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); }
We switched from if
to match
now that we have three cases. We need to
explicitly match on a slice of request_line
to pattern match against the
string literal values; match
doesn’t do automatic referencing and
dereferencing like the equality method does.
The first arm is the same as the if
block from Listing 20-9. The second arm
matches a request to /sleep. When that request is received, the server will
sleep for 5 seconds before rendering the successful HTML page. The third arm is
the same as the else
block from Listing 20-9.
You can see how primitive our server is: real libraries would handle the recognition of multiple requests in a much less verbose way!
Start the server using cargo run
. Then open two browser windows: one for
http://127.0.0.1:7878/ and the other for http://127.0.0.1:7878/sleep. If
you enter the / URI a few times, as before, you’ll see it respond quickly.
But if you enter /sleep and then load /, you’ll see that / waits until
sleep
has slept for its full 5 seconds before loading.
There are multiple techniques we could use to avoid requests backing up behind a slow request; the one we’ll implement is a thread pool.
Improving Throughput with a Thread Pool
A thread pool is a group of spawned threads that are waiting and ready to handle a task. When the program receives a new task, it assigns one of the threads in the pool to the task, and that thread will process the task. The remaining threads in the pool are available to handle any other tasks that come in while the first thread is processing. When the first thread is done processing its task, it’s returned to the pool of idle threads, ready to handle a new task. A thread pool allows you to process connections concurrently, increasing the throughput of your server.
We’ll limit the number of threads in the pool to a small number to protect us from Denial of Service (DoS) attacks; if we had our program create a new thread for each request as it came in, someone making 10 million requests to our server could create havoc by using up all our server’s resources and grinding the processing of requests to a halt.
Rather than spawning unlimited threads, then, we’ll have a fixed number of
threads waiting in the pool. Requests that come in are sent to the pool for
processing. The pool will maintain a queue of incoming requests. Each of the
threads in the pool will pop off a request from this queue, handle the request,
and then ask the queue for another request. With this design, we can process up
to N
requests concurrently, where N
is the number of threads. If each
thread is responding to a long-running request, subsequent requests can still
back up in the queue, but we’ve increased the number of long-running requests
we can handle before reaching that point.
This technique is just one of many ways to improve the throughput of a web server. Other options you might explore are the fork/join model, the single-threaded async I/O model, or the multi-threaded async I/O model. If you’re interested in this topic, you can read more about other solutions and try to implement them; with a low-level language like Rust, all of these options are possible.
Before we begin implementing a thread pool, let’s talk about what using the pool should look like. When you’re trying to design code, writing the client interface first can help guide your design. Write the API of the code so it’s structured in the way you want to call it; then implement the functionality within that structure rather than implementing the functionality and then designing the public API.
Similar to how we used test-driven development in the project in Chapter 12, we’ll use compiler-driven development here. We’ll write the code that calls the functions we want, and then we’ll look at errors from the compiler to determine what we should change next to get the code to work. Before we do that, however, we’ll explore the technique we’re not going to use as a starting point.
Spawning a Thread for Each Request
First, let’s explore how our code might look if it did create a new thread for
every connection. As mentioned earlier, this isn’t our final plan due to the
problems with potentially spawning an unlimited number of threads, but it is a
starting point to get a working multithreaded server first. Then we’ll add the
thread pool as an improvement, and contrasting the two solutions will be
easier. Listing 20-11 shows the changes to make to main
to spawn a new thread
to handle each stream within the for
loop.
Filename: src/main.rs
use std::{ fs, io::{prelude::*, BufReader}, net::{TcpListener, TcpStream}, thread, time::Duration, }; fn main() { let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); for stream in listener.incoming() { let stream = stream.unwrap(); thread::spawn(|| { handle_connection(stream); }); } } fn handle_connection(mut stream: TcpStream) { let buf_reader = BufReader::new(&mut stream); let request_line = buf_reader.lines().next().unwrap().unwrap(); let (status_line, filename) = match &request_line[..] { "GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"), "GET /sleep HTTP/1.1" => { thread::sleep(Duration::from_secs(5)); ("HTTP/1.1 200 OK", "hello.html") } _ => ("HTTP/1.1 404 NOT FOUND", "404.html"), }; let contents = fs::read_to_string(filename).unwrap(); let length = contents.len(); let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}"); stream.write_all(response.as_bytes()).unwrap(); }
As you learned in Chapter 16, thread::spawn
will create a new thread and then
run the code in the closure in the new thread. If you run this code and load
/sleep in your browser, then / in two more browser tabs, you’ll indeed see
that the requests to / don’t have to wait for /sleep to finish. However, as
we mentioned, this will eventually overwhelm the system because you’d be making
new threads without any limit.
Creating a Finite Number of Threads
We want our thread pool to work in a similar, familiar way so switching from
threads to a thread pool doesn’t require large changes to the code that uses
our API. Listing 20-12 shows the hypothetical interface for a ThreadPool
struct we want to use instead of thread::spawn
.
Filename: src/main.rs
use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
thread,
time::Duration,
};
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
}
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&mut stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap();
}
We use ThreadPool::new
to create a new thread pool with a configurable number
of threads, in this case four. Then, in the for
loop, pool.execute
has a
similar interface as thread::spawn
in that it takes a closure the pool should
run for each stream. We need to implement pool.execute
so it takes the
closure and gives it to a thread in the pool to run. This code won’t yet
compile, but we’ll try so the compiler can guide us in how to fix it.
Building ThreadPool
Using Compiler Driven Development
Make the changes in Listing 20-12 to src/main.rs, and then let’s use the
compiler errors from cargo check
to drive our development. Here is the first
error we get:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0433]: failed to resolve: use of undeclared type `ThreadPool`
--> src/main.rs:11:16
|
11 | let pool = ThreadPool::new(4);
| ^^^^^^^^^^ use of undeclared type `ThreadPool`
For more information about this error, try `rustc --explain E0433`.
error: could not compile `hello` due to previous error
Great! This error tells us we need a ThreadPool
type or module, so we’ll
build one now. Our ThreadPool
implementation will be independent of the kind
of work our web server is doing. So, let’s switch the hello
crate from a
binary crate to a library crate to hold our ThreadPool
implementation. After
we change to a library crate, we could also use the separate thread pool
library for any work we want to do using a thread pool, not just for serving
web requests.
Create a src/lib.rs that contains the following, which is the simplest
definition of a ThreadPool
struct that we can have for now:
Filename: src/lib.rs
pub struct ThreadPool;
Then edit main.rs file to bring ThreadPool
into scope from the library
crate by adding the following code to the top of src/main.rs:
Filename: src/main.rs
use hello::ThreadPool;
use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
thread,
time::Duration,
};
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
}
fn handle_connection(mut stream: TcpStream) {
let buf_reader = BufReader::new(&mut stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap();
}
This code still won’t work, but let’s check it again to get the next error that we need to address:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no function or associated item named `new` found for struct `ThreadPool` in the current scope
--> src/main.rs:12:28
|
12 | let pool = ThreadPool::new(4);
| ^^^ function or associated item not found in `ThreadPool`
For more information about this error, try `rustc --explain E0599`.
error: could not compile `hello` due to previous error
This error indicates that next we need to create an associated function named
new
for ThreadPool
. We also know that new
needs to have one parameter
that can accept 4
as an argument and should return a ThreadPool
instance.
Let’s implement the simplest new
function that will have those
characteristics:
Filename: src/lib.rs
pub struct ThreadPool;
impl ThreadPool {
pub fn new(size: usize) -> ThreadPool {
ThreadPool
}
}
We chose usize
as the type of the size
parameter, because we know that a
negative number of threads doesn’t make any sense. We also know we’ll use this
4 as the number of elements in a collection of threads, which is what the
usize
type is for, as discussed in the “Integer Types” section of Chapter 3.
Let’s check the code again:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `execute` found for struct `ThreadPool` in the current scope
--> src/main.rs:17:14
|
17 | pool.execute(|| {
| ^^^^^^^ method not found in `ThreadPool`
For more information about this error, try `rustc --explain E0599`.
error: could not compile `hello` due to previous error
Now the error occurs because we don’t have an execute
method on ThreadPool
.
Recall from the “Creating a Finite Number of
Threads” section that we
decided our thread pool should have an interface similar to thread::spawn
. In
addition, we’ll implement the execute
function so it takes the closure it’s
given and gives it to an idle thread in the pool to run.
We’ll define the execute
method on ThreadPool
to take a closure as a
parameter. Recall from the “Moving Captured Values Out of the Closure and the
Fn
Traits” section in Chapter 13 that we can take
closures as parameters with three different traits: Fn
, FnMut
, and
FnOnce
. We need to decide which kind of closure to use here. We know we’ll
end up doing something similar to the standard library thread::spawn
implementation, so we can look at what bounds the signature of thread::spawn
has on its parameter. The documentation shows us the following:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
The F
type parameter is the one we’re concerned with here; the T
type
parameter is related to the return value, and we’re not concerned with that. We
can see that spawn
uses FnOnce
as the trait bound on F
. This is probably
what we want as well, because we’ll eventually pass the argument we get in
execute
to spawn
. We can be further confident that FnOnce
is the trait we
want to use because the thread for running a request will only execute that
request’s closure one time, which matches the Once
in FnOnce
.
The F
type parameter also has the trait bound Send
and the lifetime bound
'static
, which are useful in our situation: we need Send
to transfer the
closure from one thread to another and 'static
because we don’t know how long
the thread will take to execute. Let’s create an execute
method on
ThreadPool
that will take a generic parameter of type F
with these bounds:
Filename: src/lib.rs
pub struct ThreadPool;
impl ThreadPool {
// --snip--
pub fn new(size: usize) -> ThreadPool {
ThreadPool
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
We still use the ()
after FnOnce
because this FnOnce
represents a closure
that takes no parameters and returns the unit type ()
. Just like function
definitions, the return type can be omitted from the signature, but even if we
have no parameters, we still need the parentheses.
Again, this is the simplest implementation of the execute
method: it does
nothing, but we’re trying only to make our code compile. Let’s check it again:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.24s
It compiles! But note that if you try cargo run
and make a request in the
browser, you’ll see the errors in the browser that we saw at the beginning of
the chapter. Our library isn’t actually calling the closure passed to execute
yet!
Note: A saying you might hear about languages with strict compilers, such as Haskell and Rust, is “if the code compiles, it works.” But this saying is not universally true. Our project compiles, but it does absolutely nothing! If we were building a real, complete project, this would be a good time to start writing unit tests to check that the code compiles and has the behavior we want.
Validating the Number of Threads in new
We aren’t doing anything with the parameters to new
and execute
. Let’s
implement the bodies of these functions with the behavior we want. To start,
let’s think about new
. Earlier we chose an unsigned type for the size
parameter, because a pool with a negative number of threads makes no sense.
However, a pool with zero threads also makes no sense, yet zero is a perfectly
valid usize
. We’ll add code to check that size
is greater than zero before
we return a ThreadPool
instance and have the program panic if it receives a
zero by using the assert!
macro, as shown in Listing 20-13.
Filename: src/lib.rs
pub struct ThreadPool;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
ThreadPool
}
// --snip--
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
We’ve also added some documentation for our ThreadPool
with doc comments.
Note that we followed good documentation practices by adding a section that
calls out the situations in which our function can panic, as discussed in
Chapter 14. Try running cargo doc --open
and clicking the ThreadPool
struct
to see what the generated docs for new
look like!
Instead of adding the assert!
macro as we’ve done here, we could change new
into build
and return a Result
like we did with Config::build
in the I/O
project in Listing 12-9. But we’ve decided in this case that trying to create a
thread pool without any threads should be an unrecoverable error. If you’re
feeling ambitious, try to write a function named build
with the following
signature to compare with the new
function:
pub fn build(size: usize) -> Result<ThreadPool, PoolCreationError> {
Creating Space to Store the Threads
Now that we have a way to know we have a valid number of threads to store in
the pool, we can create those threads and store them in the ThreadPool
struct
before returning the struct. But how do we “store” a thread? Let’s take another
look at the thread::spawn
signature:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
The spawn
function returns a JoinHandle<T>
, where T
is the type that the
closure returns. Let’s try using JoinHandle
too and see what happens. In our
case, the closures we’re passing to the thread pool will handle the connection
and not return anything, so T
will be the unit type ()
.
The code in Listing 20-14 will compile but doesn’t create any threads yet.
We’ve changed the definition of ThreadPool
to hold a vector of
thread::JoinHandle<()>
instances, initialized the vector with a capacity of
size
, set up a for
loop that will run some code to create the threads, and
returned a ThreadPool
instance containing them.
Filename: src/lib.rs
use std::thread;
pub struct ThreadPool {
threads: Vec<thread::JoinHandle<()>>,
}
impl ThreadPool {
// --snip--
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let mut threads = Vec::with_capacity(size);
for _ in 0..size {
// create some threads and store them in the vector
}
ThreadPool { threads }
}
// --snip--
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
We’ve brought std::thread
into scope in the library crate, because we’re
using thread::JoinHandle
as the type of the items in the vector in
ThreadPool
.
Once a valid size is received, our ThreadPool
creates a new vector that can
hold size
items. The with_capacity
function performs the same task as
Vec::new
but with an important difference: it preallocates space in the
vector. Because we know we need to store size
elements in the vector, doing
this allocation up front is slightly more efficient than using Vec::new
,
which resizes itself as elements are inserted.
When you run cargo check
again, it should succeed.
A Worker
Struct Responsible for Sending Code from the ThreadPool
to a Thread
We left a comment in the for
loop in Listing 20-14 regarding the creation of
threads. Here, we’ll look at how we actually create threads. The standard
library provides thread::spawn
as a way to create threads, and
thread::spawn
expects to get some code the thread should run as soon as the
thread is created. However, in our case, we want to create the threads and have
them wait for code that we’ll send later. The standard library’s
implementation of threads doesn’t include any way to do that; we have to
implement it manually.
We’ll implement this behavior by introducing a new data structure between the
ThreadPool
and the threads that will manage this new behavior. We’ll call
this data structure Worker, which is a common term in pooling
implementations. The Worker picks up code that needs to be run and runs the
code in the Worker’s thread. Think of people working in the kitchen at a
restaurant: the workers wait until orders come in from customers, and then
they’re responsible for taking those orders and fulfilling them.
Instead of storing a vector of JoinHandle<()>
instances in the thread pool,
we’ll store instances of the Worker
struct. Each Worker
will store a single
JoinHandle<()>
instance. Then we’ll implement a method on Worker
that will
take a closure of code to run and send it to the already running thread for
execution. We’ll also give each worker an id
so we can distinguish between
the different workers in the pool when logging or debugging.
Here is the new process that will happen when we create a ThreadPool
. We’ll
implement the code that sends the closure to the thread after we have Worker
set up in this way:
- Define a
Worker
struct that holds anid
and aJoinHandle<()>
. - Change
ThreadPool
to hold a vector ofWorker
instances. - Define a
Worker::new
function that takes anid
number and returns aWorker
instance that holds theid
and a thread spawned with an empty closure. - In
ThreadPool::new
, use thefor
loop counter to generate anid
, create a newWorker
with thatid
, and store the worker in the vector.
If you’re up for a challenge, try implementing these changes on your own before looking at the code in Listing 20-15.
Ready? Here is Listing 20-15 with one way to make the preceding modifications.
Filename: src/lib.rs
use std::thread;
pub struct ThreadPool {
workers: Vec<Worker>,
}
impl ThreadPool {
// --snip--
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id));
}
ThreadPool { workers }
}
// --snip--
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize) -> Worker {
let thread = thread::spawn(|| {});
Worker { id, thread }
}
}
We’ve changed the name of the field on ThreadPool
from threads
to workers
because it’s now holding Worker
instances instead of JoinHandle<()>
instances. We use the counter in the for
loop as an argument to
Worker::new
, and we store each new Worker
in the vector named workers
.
External code (like our server in src/main.rs) doesn’t need to know the
implementation details regarding using a Worker
struct within ThreadPool
,
so we make the Worker
struct and its new
function private. The
Worker::new
function uses the id
we give it and stores a JoinHandle<()>
instance that is created by spawning a new thread using an empty closure.
Note: If the operating system can’t create a thread because there aren’t enough system resources,
thread::spawn
will panic. That will cause our whole server to panic, even though the creation of some threads might succeed. For simplicity’s sake, this behavior is fine, but in a production thread pool implementation, you’d likely want to usestd::thread::Builder
and itsspawn
method that returnsResult
instead.
This code will compile and will store the number of Worker
instances we
specified as an argument to ThreadPool::new
. But we’re still not processing
the closure that we get in execute
. Let’s look at how to do that next.
Sending Requests to Threads via Channels
The next problem we’ll tackle is that the closures given to thread::spawn
do
absolutely nothing. Currently, we get the closure we want to execute in the
execute
method. But we need to give thread::spawn
a closure to run when we
create each Worker
during the creation of the ThreadPool
.
We want the Worker
structs that we just created to fetch the code to run from
a queue held in the ThreadPool
and send that code to its thread to run.
The channels we learned about in Chapter 16—a simple way to communicate between
two threads—would be perfect for this use case. We’ll use a channel to function
as the queue of jobs, and execute
will send a job from the ThreadPool
to
the Worker
instances, which will send the job to its thread. Here is the plan:
- The
ThreadPool
will create a channel and hold on to the sender. - Each
Worker
will hold on to the receiver. - We’ll create a new
Job
struct that will hold the closures we want to send down the channel. - The
execute
method will send the job it wants to execute through the sender. - In its thread, the
Worker
will loop over its receiver and execute the closures of any jobs it receives.
Let’s start by creating a channel in ThreadPool::new
and holding the sender
in the ThreadPool
instance, as shown in Listing 20-16. The Job
struct
doesn’t hold anything for now but will be the type of item we’re sending down
the channel.
Filename: src/lib.rs
use std::{sync::mpsc, thread};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
struct Job;
impl ThreadPool {
// --snip--
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id));
}
ThreadPool { workers, sender }
}
// --snip--
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize) -> Worker {
let thread = thread::spawn(|| {});
Worker { id, thread }
}
}
In ThreadPool::new
, we create our new channel and have the pool hold the
sender. This will successfully compile.
Let’s try passing a receiver of the channel into each worker as the thread pool
creates the channel. We know we want to use the receiver in the thread that the
workers spawn, so we’ll reference the receiver
parameter in the closure. The
code in Listing 20-17 won’t quite compile yet.
Filename: src/lib.rs
use std::{sync::mpsc, thread};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
struct Job;
impl ThreadPool {
// --snip--
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, receiver));
}
ThreadPool { workers, sender }
}
// --snip--
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
// --snip--
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: mpsc::Receiver<Job>) -> Worker {
let thread = thread::spawn(|| {
receiver;
});
Worker { id, thread }
}
}
We’ve made some small and straightforward changes: we pass the receiver into
Worker::new
, and then we use it inside the closure.
When we try to check this code, we get this error:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0382]: use of moved value: `receiver`
--> src/lib.rs:26:42
|
21 | let (sender, receiver) = mpsc::channel();
| -------- move occurs because `receiver` has type `std::sync::mpsc::Receiver<Job>`, which does not implement the `Copy` trait
...
26 | workers.push(Worker::new(id, receiver));
| ^^^^^^^^ value moved here, in previous iteration of loop
For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` due to previous error
The code is trying to pass receiver
to multiple Worker
instances. This
won’t work, as you’ll recall from Chapter 16: the channel implementation that
Rust provides is multiple producer, single consumer. This means we can’t
just clone the consuming end of the channel to fix this code. We also don’t
want to send a message multiple times to multiple consumers; we want one list
of messages with multiple workers such that each message gets processed once.
Additionally, taking a job off the channel queue involves mutating the
receiver
, so the threads need a safe way to share and modify receiver
;
otherwise, we might get race conditions (as covered in Chapter 16).
Recall the thread-safe smart pointers discussed in Chapter 16: to share
ownership across multiple threads and allow the threads to mutate the value, we
need to use Arc<Mutex<T>>
. The Arc
type will let multiple workers own the
receiver, and Mutex
will ensure that only one worker gets a job from the
receiver at a time. Listing 20-18 shows the changes we need to make.
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
// --snip--
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
struct Job;
impl ThreadPool {
// --snip--
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
// --snip--
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
}
}
// --snip--
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
// --snip--
let thread = thread::spawn(|| {
receiver;
});
Worker { id, thread }
}
}
In ThreadPool::new
, we put the receiver in an Arc
and a Mutex
. For each
new worker, we clone the Arc
to bump the reference count so the workers can
share ownership of the receiver.
With these changes, the code compiles! We’re getting there!
Implementing the execute
Method
Let’s finally implement the execute
method on ThreadPool
. We’ll also change
Job
from a struct to a type alias for a trait object that holds the type of
closure that execute
receives. As discussed in the “Creating Type Synonyms
with Type Aliases”
section of Chapter 19, type aliases allow us to make long types shorter for
ease of use. Look at Listing 20-19.
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
// --snip--
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
// --snip--
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
// --snip--
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(|| {
receiver;
});
Worker { id, thread }
}
}
After creating a new Job
instance using the closure we get in execute
, we
send that job down the sending end of the channel. We’re calling unwrap
on
send
for the case that sending fails. This might happen if, for example, we
stop all our threads from executing, meaning the receiving end has stopped
receiving new messages. At the moment, we can’t stop our threads from
executing: our threads continue executing as long as the pool exists. The
reason we use unwrap
is that we know the failure case won’t happen, but the
compiler doesn’t know that.
But we’re not quite done yet! In the worker, our closure being passed to
thread::spawn
still only references the receiving end of the channel.
Instead, we need the closure to loop forever, asking the receiving end of the
channel for a job and running the job when it gets one. Let’s make the change
shown in Listing 20-20 to Worker::new
.
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
// --snip--
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker { id, thread }
}
}
Here, we first call lock
on the receiver
to acquire the mutex, and then we
call unwrap
to panic on any errors. Acquiring a lock might fail if the mutex
is in a poisoned state, which can happen if some other thread panicked while
holding the lock rather than releasing the lock. In this situation, calling
unwrap
to have this thread panic is the correct action to take. Feel free to
change this unwrap
to an expect
with an error message that is meaningful to
you.
If we get the lock on the mutex, we call recv
to receive a Job
from the
channel. A final unwrap
moves past any errors here as well, which might occur
if the thread holding the sender has shut down, similar to how the send
method returns Err
if the receiver shuts down.
The call to recv
blocks, so if there is no job yet, the current thread will
wait until a job becomes available. The Mutex<T>
ensures that only one
Worker
thread at a time is trying to request a job.
Our thread pool is now in a working state! Give it a cargo run
and make some
requests:
$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
warning: field is never read: `workers`
--> src/lib.rs:7:5
|
7 | workers: Vec<Worker>,
| ^^^^^^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: field is never read: `id`
--> src/lib.rs:48:5
|
48 | id: usize,
| ^^^^^^^^^
warning: field is never read: `thread`
--> src/lib.rs:49:5
|
49 | thread: thread::JoinHandle<()>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
warning: `hello` (lib) generated 3 warnings
Finished dev [unoptimized + debuginfo] target(s) in 1.40s
Running `target/debug/hello`
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Worker 1 got a job; executing.
Worker 3 got a job; executing.
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Worker 1 got a job; executing.
Worker 3 got a job; executing.
Worker 0 got a job; executing.
Worker 2 got a job; executing.
Success! We now have a thread pool that executes connections asynchronously. There are never more than four threads created, so our system won’t get overloaded if the server receives a lot of requests. If we make a request to /sleep, the server will be able to serve other requests by having another thread run them.
Note: if you open /sleep in multiple browser windows simultaneously, they might load one at a time in 5 second intervals. Some web browsers execute multiple instances of the same request sequentially for caching reasons. This limitation is not caused by our web server.
After learning about the while let
loop in Chapter 18, you might be wondering
why we didn’t write the worker thread code as shown in Listing 20-21.
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
// --snip--
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || {
while let Ok(job) = receiver.lock().unwrap().recv() {
println!("Worker {id} got a job; executing.");
job();
}
});
Worker { id, thread }
}
}
This code compiles and runs but doesn’t result in the desired threading
behavior: a slow request will still cause other requests to wait to be
processed. The reason is somewhat subtle: the Mutex
struct has no public
unlock
method because the ownership of the lock is based on the lifetime of
the MutexGuard<T>
within the LockResult<MutexGuard<T>>
that the lock
method returns. At compile time, the borrow checker can then enforce the rule
that a resource guarded by a Mutex
cannot be accessed unless we hold the
lock. However, this implementation can also result in the lock being held
longer than intended if we aren’t mindful of the lifetime of the
MutexGuard<T>
.
The code in Listing 20-20 that uses let job = receiver.lock().unwrap().recv().unwrap();
works because with let
, any
temporary values used in the expression on the right hand side of the equals
sign are immediately dropped when the let
statement ends. However, while let
(and if let
and match
) does not drop temporary values until the end of
the associated block. In Listing 20-21, the lock remains held for the duration
of the call to job()
, meaning other workers cannot receive jobs.
Graceful Shutdown and Cleanup
The code in Listing 20-20 is responding to requests asynchronously through the
use of a thread pool, as we intended. We get some warnings about the workers
,
id
, and thread
fields that we’re not using in a direct way that reminds us
we’re not cleaning up anything. When we use the less elegant ctrl-c method to halt the main thread, all other
threads are stopped immediately as well, even if they’re in the middle of
serving a request.
Next, then, we’ll implement the Drop
trait to call join
on each of the
threads in the pool so they can finish the requests they’re working on before
closing. Then we’ll implement a way to tell the threads they should stop
accepting new requests and shut down. To see this code in action, we’ll modify
our server to accept only two requests before gracefully shutting down its
thread pool.
Implementing the Drop
Trait on ThreadPool
Let’s start with implementing Drop
on our thread pool. When the pool is
dropped, our threads should all join to make sure they finish their work.
Listing 20-22 shows a first attempt at a Drop
implementation; this code won’t
quite work yet.
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
worker.thread.join().unwrap();
}
}
}
struct Worker {
id: usize,
thread: thread::JoinHandle<()>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker { id, thread }
}
}
First, we loop through each of the thread pool workers
. We use &mut
for
this because self
is a mutable reference, and we also need to be able to
mutate worker
. For each worker, we print a message saying that this
particular worker is shutting down, and then we call join
on that worker’s
thread. If the call to join
fails, we use unwrap
to make Rust panic and go
into an ungraceful shutdown.
Here is the error we get when we compile this code:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0507]: cannot move out of `worker.thread` which is behind a mutable reference
--> src/lib.rs:52:13
|
52 | worker.thread.join().unwrap();
| ^^^^^^^^^^^^^ ------ `worker.thread` moved due to this method call
| |
| move occurs because `worker.thread` has type `JoinHandle<()>`, which does not implement the `Copy` trait
|
note: this function takes ownership of the receiver `self`, which moves `worker.thread`
--> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:1581:17
For more information about this error, try `rustc --explain E0507`.
error: could not compile `hello` due to previous error
The error tells us we can’t call join
because we only have a mutable borrow
of each worker
and join
takes ownership of its argument. To solve this
issue, we need to move the thread out of the Worker
instance that owns
thread
so join
can consume the thread. We did this in Listing 17-15: if
Worker
holds an Option<thread::JoinHandle<()>>
instead, we can call the
take
method on the Option
to move the value out of the Some
variant and
leave a None
variant in its place. In other words, a Worker
that is running
will have a Some
variant in thread
, and when we want to clean up a
Worker
, we’ll replace Some
with None
so the Worker
doesn’t have a
thread to run.
So we know we want to update the definition of Worker
like this:
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
worker.thread.join().unwrap();
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker { id, thread }
}
}
Now let’s lean on the compiler to find the other places that need to change. Checking this code, we get two errors:
$ cargo check
Checking hello v0.1.0 (file:///projects/hello)
error[E0599]: no method named `join` found for enum `Option` in the current scope
--> src/lib.rs:52:27
|
52 | worker.thread.join().unwrap();
| ^^^^ method not found in `Option<JoinHandle<()>>`
|
note: the method `join` exists on the type `JoinHandle<()>`
--> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:1581:5
help: consider using `Option::expect` to unwrap the `JoinHandle<()>` value, panicking if the value is an `Option::None`
|
52 | worker.thread.expect("REASON").join().unwrap();
| +++++++++++++++++
error[E0308]: mismatched types
--> src/lib.rs:72:22
|
72 | Worker { id, thread }
| ^^^^^^ expected enum `Option`, found struct `JoinHandle`
|
= note: expected enum `Option<JoinHandle<()>>`
found struct `JoinHandle<_>`
help: try wrapping the expression in `Some`
|
72 | Worker { id, thread: Some(thread) }
| +++++++++++++ +
Some errors have detailed explanations: E0308, E0599.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `hello` due to 2 previous errors
Let’s address the second error, which points to the code at the end of
Worker::new
; we need to wrap the thread
value in Some
when we create a
new Worker
. Make the following changes to fix this error:
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
worker.thread.join().unwrap();
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
// --snip--
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker {
id,
thread: Some(thread),
}
}
}
The first error is in our Drop
implementation. We mentioned earlier that we
intended to call take
on the Option
value to move thread
out of worker
.
The following changes will do so:
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: mpsc::Sender<Job>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool { workers, sender }
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker {
id,
thread: Some(thread),
}
}
}
As discussed in Chapter 17, the take
method on Option
takes the Some
variant out and leaves None
in its place. We’re using if let
to destructure
the Some
and get the thread; then we call join
on the thread. If a worker’s
thread is already None
, we know that worker has already had its thread
cleaned up, so nothing happens in that case.
Signaling to the Threads to Stop Listening for Jobs
With all the changes we’ve made, our code compiles without any warnings.
However, the bad news is this code doesn’t function the way we want it to yet.
The key is the logic in the closures run by the threads of the Worker
instances: at the moment, we call join
, but that won’t shut down the threads
because they loop
forever looking for jobs. If we try to drop our
ThreadPool
with our current implementation of drop
, the main thread will
block forever waiting for the first thread to finish.
To fix this problem, we’ll need a change in the ThreadPool
drop
implementation and then a change in the Worker
loop.
First, we’ll change the ThreadPool
drop
implementation to explicitly drop
the sender
before waiting for the threads to finish. Listing 20-23 shows the
changes to ThreadPool
to explicitly drop sender
. We use the same Option
and take
technique as we did with the thread to be able to move sender
out
of ThreadPool
:
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
// --snip--
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
// --snip--
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool {
workers,
sender: Some(sender),
}
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.as_ref().unwrap().send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
drop(self.sender.take());
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let job = receiver.lock().unwrap().recv().unwrap();
println!("Worker {id} got a job; executing.");
job();
});
Worker {
id,
thread: Some(thread),
}
}
}
Dropping sender
closes the channel, which indicates no more messages will be
sent. When that happens, all the calls to recv
that the workers do in the
infinite loop will return an error. In Listing 20-24, we change the Worker
loop to gracefully exit the loop in that case, which means the threads will
finish when the ThreadPool
drop
implementation calls join
on them.
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool {
workers,
sender: Some(sender),
}
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.as_ref().unwrap().send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
drop(self.sender.take());
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) => {
println!("Worker {id} got a job; executing.");
job();
}
Err(_) => {
println!("Worker {id} disconnected; shutting down.");
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}
To see this code in action, let’s modify main
to accept only two requests
before gracefully shutting down the server, as shown in Listing 20-25.
Filename: src/main.rs
use hello::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
You wouldn’t want a real-world web server to shut down after serving only two requests. This code just demonstrates that the graceful shutdown and cleanup is in working order.
The take
method is defined in the Iterator
trait and limits the iteration
to the first two items at most. The ThreadPool
will go out of scope at the
end of main
, and the drop
implementation will run.
Start the server with cargo run
, and make three requests. The third request
should error, and in your terminal you should see output similar to this:
$ cargo run
Compiling hello v0.1.0 (file:///projects/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.0s
Running `target/debug/hello`
Worker 0 got a job; executing.
Shutting down.
Shutting down worker 0
Worker 3 got a job; executing.
Worker 1 disconnected; shutting down.
Worker 2 disconnected; shutting down.
Worker 3 disconnected; shutting down.
Worker 0 disconnected; shutting down.
Shutting down worker 1
Shutting down worker 2
Shutting down worker 3
You might see a different ordering of workers and messages printed. We can see
how this code works from the messages: workers 0 and 3 got the first two
requests. The server stopped accepting connections after the second connection,
and the Drop
implementation on ThreadPool
starts executing before worker 3
even starts its job. Dropping the sender
disconnects all the workers and
tells them to shut down. The workers each print a message when they disconnect,
and then the thread pool calls join
to wait for each worker thread to finish.
Notice one interesting aspect of this particular execution: the ThreadPool
dropped the sender
, and before any worker received an error, we tried to join
worker 0. Worker 0 had not yet gotten an error from recv
, so the main thread
blocked waiting for worker 0 to finish. In the meantime, worker 3 received a
job and then all threads received an error. When worker 0 finished, the main
thread waited for the rest of the workers to finish. At that point, they had
all exited their loops and stopped.
Congrats! We’ve now completed our project; we have a basic web server that uses a thread pool to respond asynchronously. We’re able to perform a graceful shutdown of the server, which cleans up all the threads in the pool.
Here’s the full code for reference:
Filename: src/main.rs
use hello::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4);
for stream in listener.incoming().take(2) {
let stream = stream.unwrap();
pool.execute(|| {
handle_connection(stream);
});
}
println!("Shutting down.");
}
fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
};
let contents = fs::read_to_string(filename).unwrap();
let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
Filename: src/lib.rs
use std::{
sync::{mpsc, Arc, Mutex},
thread,
};
pub struct ThreadPool {
workers: Vec<Worker>,
sender: Option<mpsc::Sender<Job>>,
}
type Job = Box<dyn FnOnce() + Send + 'static>;
impl ThreadPool {
/// Create a new ThreadPool.
///
/// The size is the number of threads in the pool.
///
/// # Panics
///
/// The `new` function will panic if the size is zero.
pub fn new(size: usize) -> ThreadPool {
assert!(size > 0);
let (sender, receiver) = mpsc::channel();
let receiver = Arc::new(Mutex::new(receiver));
let mut workers = Vec::with_capacity(size);
for id in 0..size {
workers.push(Worker::new(id, Arc::clone(&receiver)));
}
ThreadPool {
workers,
sender: Some(sender),
}
}
pub fn execute<F>(&self, f: F)
where
F: FnOnce() + Send + 'static,
{
let job = Box::new(f);
self.sender.as_ref().unwrap().send(job).unwrap();
}
}
impl Drop for ThreadPool {
fn drop(&mut self) {
drop(self.sender.take());
for worker in &mut self.workers {
println!("Shutting down worker {}", worker.id);
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
}
}
}
struct Worker {
id: usize,
thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Worker {
let thread = thread::spawn(move || loop {
let message = receiver.lock().unwrap().recv();
match message {
Ok(job) => {
println!("Worker {id} got a job; executing.");
job();
}
Err(_) => {
println!("Worker {id} disconnected; shutting down.");
break;
}
}
});
Worker {
id,
thread: Some(thread),
}
}
}
We could do more here! If you want to continue enhancing this project, here are some ideas:
- Add more documentation to
ThreadPool
and its public methods. - Add tests of the library’s functionality.
- Change calls to
unwrap
to more robust error handling. - Use
ThreadPool
to perform some task other than serving web requests. - Find a thread pool crate on crates.io and implement a similar web server using the crate instead. Then compare its API and robustness to the thread pool we implemented.
Summary
Well done! You’ve made it to the end of the book! We want to thank you for joining us on this tour of Rust. You’re now ready to implement your own Rust projects and help with other peoples’ projects. Keep in mind that there is a welcoming community of other Rustaceans who would love to help you with any challenges you encounter on your Rust journey.
Appendix
The following sections contain reference material you may find useful in your Rust journey.
Appendix A: Keywords
The following list contains keywords that are reserved for current or future use by the Rust language. As such, they cannot be used as identifiers (except as raw identifiers as we’ll discuss in the “Raw Identifiers” section). Identifiers are names of functions, variables, parameters, struct fields, modules, crates, constants, macros, static values, attributes, types, traits, or lifetimes.
Keywords Currently in Use
The following is a list of keywords currently in use, with their functionality described.
as
- perform primitive casting, disambiguate the specific trait containing an item, or rename items inuse
statementsasync
- return aFuture
instead of blocking the current threadawait
- suspend execution until the result of aFuture
is readybreak
- exit a loop immediatelyconst
- define constant items or constant raw pointerscontinue
- continue to the next loop iterationcrate
- in a module path, refers to the crate rootdyn
- dynamic dispatch to a trait objectelse
- fallback forif
andif let
control flow constructsenum
- define an enumerationextern
- link an external function or variablefalse
- Boolean false literalfn
- define a function or the function pointer typefor
- loop over items from an iterator, implement a trait, or specify a higher-ranked lifetimeif
- branch based on the result of a conditional expressionimpl
- implement inherent or trait functionalityin
- part offor
loop syntaxlet
- bind a variableloop
- loop unconditionallymatch
- match a value to patternsmod
- define a modulemove
- make a closure take ownership of all its capturesmut
- denote mutability in references, raw pointers, or pattern bindingspub
- denote public visibility in struct fields,impl
blocks, or modulesref
- bind by referencereturn
- return from functionSelf
- a type alias for the type we are defining or implementingself
- method subject or current modulestatic
- global variable or lifetime lasting the entire program executionstruct
- define a structuresuper
- parent module of the current moduletrait
- define a traittrue
- Boolean true literaltype
- define a type alias or associated typeunion
- define a union; is only a keyword when used in a union declarationunsafe
- denote unsafe code, functions, traits, or implementationsuse
- bring symbols into scopewhere
- denote clauses that constrain a typewhile
- loop conditionally based on the result of an expression
Keywords Reserved for Future Use
The following keywords do not yet have any functionality but are reserved by Rust for potential future use.
abstract
become
box
do
final
macro
override
priv
try
typeof
unsized
virtual
yield
Raw Identifiers
Raw identifiers are the syntax that lets you use keywords where they wouldn’t
normally be allowed. You use a raw identifier by prefixing a keyword with r#
.
For example, match
is a keyword. If you try to compile the following function
that uses match
as its name:
Filename: src/main.rs
fn match(needle: &str, haystack: &str) -> bool {
haystack.contains(needle)
}
you’ll get this error:
error: expected identifier, found keyword `match`
--> src/main.rs:4:4
|
4 | fn match(needle: &str, haystack: &str) -> bool {
| ^^^^^ expected identifier, found keyword
The error shows that you can’t use the keyword match
as the function
identifier. To use match
as a function name, you need to use the raw
identifier syntax, like this:
Filename: src/main.rs
fn r#match(needle: &str, haystack: &str) -> bool { haystack.contains(needle) } fn main() { assert!(r#match("foo", "foobar")); }
This code will compile without any errors. Note the r#
prefix on the function
name in its definition as well as where the function is called in main
.
Raw identifiers allow you to use any word you choose as an identifier, even if
that word happens to be a reserved keyword. This gives us more freedom to
choose identifier names, as well as lets us integrate with programs written in
a language where these words aren’t keywords. In addition, raw identifiers
allow you to use libraries written in a different Rust edition than your crate
uses. For example, try
isn’t a keyword in the 2015 edition but is in the 2018
edition. If you depend on a library that’s written using the 2015 edition and
has a try
function, you’ll need to use the raw identifier syntax, r#try
in
this case, to call that function from your 2018 edition code. See Appendix
E for more information on editions.
Appendix B: Operators and Symbols
This appendix contains a glossary of Rust’s syntax, including operators and other symbols that appear by themselves or in the context of paths, generics, trait bounds, macros, attributes, comments, tuples, and brackets.
Operators
Table B-1 contains the operators in Rust, an example of how the operator would appear in context, a short explanation, and whether that operator is overloadable. If an operator is overloadable, the relevant trait to use to overload that operator is listed.
Operator | Example | Explanation | Overloadable? |
---|---|---|---|
! | ident!(...) , ident!{...} , ident![...] | Macro expansion | |
! | !expr | Bitwise or logical complement | Not |
!= | expr != expr | Nonequality comparison | PartialEq |
% | expr % expr | Arithmetic remainder | Rem |
%= | var %= expr | Arithmetic remainder and assignment | RemAssign |
& | &expr , &mut expr | Borrow | |
& | &type , &mut type , &'a type , &'a mut type | Borrowed pointer type | |
& | expr & expr | Bitwise AND | BitAnd |
&= | var &= expr | Bitwise AND and assignment | BitAndAssign |
&& | expr && expr | Short-circuiting logical AND | |
* | expr * expr | Arithmetic multiplication | Mul |
*= | var *= expr | Arithmetic multiplication and assignment | MulAssign |
* | *expr | Dereference | Deref |
* | *const type , *mut type | Raw pointer | |
+ | trait + trait , 'a + trait | Compound type constraint | |
+ | expr + expr | Arithmetic addition | Add |
+= | var += expr | Arithmetic addition and assignment | AddAssign |
, | expr, expr | Argument and element separator | |
- | - expr | Arithmetic negation | Neg |
- | expr - expr | Arithmetic subtraction | Sub |
-= | var -= expr | Arithmetic subtraction and assignment | SubAssign |
-> | fn(...) -> type , |...| -> type | Function and closure return type | |
. | expr.ident | Member access | |
.. | .. , expr.. , ..expr , expr..expr | Right-exclusive range literal | PartialOrd |
..= | ..=expr , expr..=expr | Right-inclusive range literal | PartialOrd |
.. | ..expr | Struct literal update syntax | |
.. | variant(x, ..) , struct_type { x, .. } | “And the rest” pattern binding | |
... | expr...expr | (Deprecated, use ..= instead) In a pattern: inclusive range pattern | |
/ | expr / expr | Arithmetic division | Div |
/= | var /= expr | Arithmetic division and assignment | DivAssign |
: | pat: type , ident: type | Constraints | |
: | ident: expr | Struct field initializer | |
: | 'a: loop {...} | Loop label | |
; | expr; | Statement and item terminator | |
; | [...; len] | Part of fixed-size array syntax | |
<< | expr << expr | Left-shift | Shl |
<<= | var <<= expr | Left-shift and assignment | ShlAssign |
< | expr < expr | Less than comparison | PartialOrd |
<= | expr <= expr | Less than or equal to comparison | PartialOrd |
= | var = expr , ident = type | Assignment/equivalence | |
== | expr == expr | Equality comparison | PartialEq |
=> | pat => expr | Part of match arm syntax | |
> | expr > expr | Greater than comparison | PartialOrd |
>= | expr >= expr | Greater than or equal to comparison | PartialOrd |
>> | expr >> expr | Right-shift | Shr |
>>= | var >>= expr | Right-shift and assignment | ShrAssign |
@ | ident @ pat | Pattern binding | |
^ | expr ^ expr | Bitwise exclusive OR | BitXor |
^= | var ^= expr | Bitwise exclusive OR and assignment | BitXorAssign |
| | pat | pat | Pattern alternatives | |
| | expr | expr | Bitwise OR | BitOr |
|= | var |= expr | Bitwise OR and assignment | BitOrAssign |
|| | expr || expr | Short-circuiting logical OR | |
? | expr? | Error propagation |
Non-operator Symbols
The following list contains all symbols that don’t function as operators; that is, they don’t behave like a function or method call.
Table B-2 shows symbols that appear on their own and are valid in a variety of locations.
Symbol | Explanation |
---|---|
'ident | Named lifetime or loop label |
...u8 , ...i32 , ...f64 , ...usize , etc. | Numeric literal of specific type |
"..." | String literal |
r"..." , r#"..."# , r##"..."## , etc. | Raw string literal, escape characters not processed |
b"..." | Byte string literal; constructs an array of bytes instead of a string |
br"..." , br#"..."# , br##"..."## , etc. | Raw byte string literal, combination of raw and byte string literal |
'...' | Character literal |
b'...' | ASCII byte literal |
|...| expr | Closure |
! | Always empty bottom type for diverging functions |
_ | “Ignored” pattern binding; also used to make integer literals readable |
Table B-3 shows symbols that appear in the context of a path through the module hierarchy to an item.
Symbol | Explanation |
---|---|
ident::ident | Namespace path |
::path | Path relative to the crate root (i.e., an explicitly absolute path) |
self::path | Path relative to the current module (i.e., an explicitly relative path). |
super::path | Path relative to the parent of the current module |
type::ident , <type as trait>::ident | Associated constants, functions, and types |
<type>::... | Associated item for a type that cannot be directly named (e.g., <&T>::... , <[T]>::... , etc.) |
trait::method(...) | Disambiguating a method call by naming the trait that defines it |
type::method(...) | Disambiguating a method call by naming the type for which it’s defined |
<type as trait>::method(...) | Disambiguating a method call by naming the trait and type |
Table B-4 shows symbols that appear in the context of using generic type parameters.
Symbol | Explanation |
---|---|
path<...> | Specifies parameters to generic type in a type (e.g., Vec<u8> ) |
path::<...> , method::<...> | Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>() ) |
fn ident<...> ... | Define generic function |
struct ident<...> ... | Define generic structure |
enum ident<...> ... | Define generic enumeration |
impl<...> ... | Define generic implementation |
for<...> type | Higher-ranked lifetime bounds |
type<ident=type> | A generic type where one or more associated types have specific assignments (e.g., Iterator<Item=T> ) |
Table B-5 shows symbols that appear in the context of constraining generic type parameters with trait bounds.
Symbol | Explanation |
---|---|
T: U | Generic parameter T constrained to types that implement U |
T: 'a | Generic type T must outlive lifetime 'a (meaning the type cannot transitively contain any references with lifetimes shorter than 'a ) |
T: 'static | Generic type T contains no borrowed references other than 'static ones |
'b: 'a | Generic lifetime 'b must outlive lifetime 'a |
T: ?Sized | Allow generic type parameter to be a dynamically sized type |
'a + trait , trait + trait | Compound type constraint |
Table B-6 shows symbols that appear in the context of calling or defining macros and specifying attributes on an item.
Symbol | Explanation |
---|---|
#[meta] | Outer attribute |
#![meta] | Inner attribute |
$ident | Macro substitution |
$ident:kind | Macro capture |
$(…)… | Macro repetition |
ident!(...) , ident!{...} , ident![...] | Macro invocation |
Table B-7 shows symbols that create comments.
Symbol | Explanation |
---|---|
// | Line comment |
//! | Inner line doc comment |
/// | Outer line doc comment |
/*...*/ | Block comment |
/*!...*/ | Inner block doc comment |
/**...*/ | Outer block doc comment |
Table B-8 shows symbols that appear in the context of using tuples.
Symbol | Explanation |
---|---|
() | Empty tuple (aka unit), both literal and type |
(expr) | Parenthesized expression |
(expr,) | Single-element tuple expression |
(type,) | Single-element tuple type |
(expr, ...) | Tuple expression |
(type, ...) | Tuple type |
expr(expr, ...) | Function call expression; also used to initialize tuple struct s and tuple enum variants |
expr.0 , expr.1 , etc. | Tuple indexing |
Table B-9 shows the contexts in which curly braces are used.
Context | Explanation |
---|---|
{...} | Block expression |
Type {...} | struct literal |
Table B-10 shows the contexts in which square brackets are used.
Context | Explanation |
---|---|
[...] | Array literal |
[expr; len] | Array literal containing len copies of expr |
[type; len] | Array type containing len instances of type |
expr[expr] | Collection indexing. Overloadable (Index , IndexMut ) |
expr[..] , expr[a..] , expr[..b] , expr[a..b] | Collection indexing pretending to be collection slicing, using Range , RangeFrom , RangeTo , or RangeFull as the “index” |
Appendix C: Derivable Traits
In various places in the book, we’ve discussed the derive
attribute, which
you can apply to a struct or enum definition. The derive
attribute generates
code that will implement a trait with its own default implementation on the
type you’ve annotated with the derive
syntax.
In this appendix, we provide a reference of all the traits in the standard
library that you can use with derive
. Each section covers:
- What operators and methods deriving this trait will enable
- What the implementation of the trait provided by
derive
does - What implementing the trait signifies about the type
- The conditions in which you’re allowed or not allowed to implement the trait
- Examples of operations that require the trait
If you want different behavior from that provided by the derive
attribute,
consult the standard library documentation
for each trait for details of how to manually implement them.
These traits listed here are the only ones defined by the standard library that
can be implemented on your types using derive
. Other traits defined in the
standard library don’t have sensible default behavior, so it’s up to you to
implement them in the way that makes sense for what you’re trying to accomplish.
An example of a trait that can’t be derived is Display
, which handles
formatting for end users. You should always consider the appropriate way to
display a type to an end user. What parts of the type should an end user be
allowed to see? What parts would they find relevant? What format of the data
would be most relevant to them? The Rust compiler doesn’t have this insight, so
it can’t provide appropriate default behavior for you.
The list of derivable traits provided in this appendix is not comprehensive:
libraries can implement derive
for their own traits, making the list of
traits you can use derive
with truly open-ended. Implementing derive
involves using a procedural macro, which is covered in the
“Macros” section of Chapter 19.
Debug
for Programmer Output
The Debug
trait enables debug formatting in format strings, which you
indicate by adding :?
within {}
placeholders.
The Debug
trait allows you to print instances of a type for debugging
purposes, so you and other programmers using your type can inspect an instance
at a particular point in a program’s execution.
The Debug
trait is required, for example, in use of the assert_eq!
macro.
This macro prints the values of instances given as arguments if the equality
assertion fails so programmers can see why the two instances weren’t equal.
PartialEq
and Eq
for Equality Comparisons
The PartialEq
trait allows you to compare instances of a type to check for
equality and enables use of the ==
and !=
operators.
Deriving PartialEq
implements the eq
method. When PartialEq
is derived on
structs, two instances are equal only if all fields are equal, and the
instances are not equal if any fields are not equal. When derived on enums,
each variant is equal to itself and not equal to the other variants.
The PartialEq
trait is required, for example, with the use of the
assert_eq!
macro, which needs to be able to compare two instances of a type
for equality.
The Eq
trait has no methods. Its purpose is to signal that for every value of
the annotated type, the value is equal to itself. The Eq
trait can only be
applied to types that also implement PartialEq
, although not all types that
implement PartialEq
can implement Eq
. One example of this is floating point
number types: the implementation of floating point numbers states that two
instances of the not-a-number (NaN
) value are not equal to each other.
An example of when Eq
is required is for keys in a HashMap<K, V>
so the
HashMap<K, V>
can tell whether two keys are the same.
PartialOrd
and Ord
for Ordering Comparisons
The PartialOrd
trait allows you to compare instances of a type for sorting
purposes. A type that implements PartialOrd
can be used with the <
, >
,
<=
, and >=
operators. You can only apply the PartialOrd
trait to types
that also implement PartialEq
.
Deriving PartialOrd
implements the partial_cmp
method, which returns an
Option<Ordering>
that will be None
when the values given don’t produce an
ordering. An example of a value that doesn’t produce an ordering, even though
most values of that type can be compared, is the not-a-number (NaN
) floating
point value. Calling partial_cmp
with any floating point number and the NaN
floating point value will return None
.
When derived on structs, PartialOrd
compares two instances by comparing the
value in each field in the order in which the fields appear in the struct
definition. When derived on enums, variants of the enum declared earlier in the
enum definition are considered less than the variants listed later.
The PartialOrd
trait is required, for example, for the gen_range
method
from the rand
crate that generates a random value in the range specified by a
range expression.
The Ord
trait allows you to know that for any two values of the annotated
type, a valid ordering will exist. The Ord
trait implements the cmp
method,
which returns an Ordering
rather than an Option<Ordering>
because a valid
ordering will always be possible. You can only apply the Ord
trait to types
that also implement PartialOrd
and Eq
(and Eq
requires PartialEq
). When
derived on structs and enums, cmp
behaves the same way as the derived
implementation for partial_cmp
does with PartialOrd
.
An example of when Ord
is required is when storing values in a BTreeSet<T>
,
a data structure that stores data based on the sort order of the values.
Clone
and Copy
for Duplicating Values
The Clone
trait allows you to explicitly create a deep copy of a value, and
the duplication process might involve running arbitrary code and copying heap
data. See the “Ways Variables and Data Interact:
Clone” section in
Chapter 4 for more information on Clone
.
Deriving Clone
implements the clone
method, which when implemented for the
whole type, calls clone
on each of the parts of the type. This means all the
fields or values in the type must also implement Clone
to derive Clone
.
An example of when Clone
is required is when calling the to_vec
method on a
slice. The slice doesn’t own the type instances it contains, but the vector
returned from to_vec
will need to own its instances, so to_vec
calls
clone
on each item. Thus, the type stored in the slice must implement Clone
.
The Copy
trait allows you to duplicate a value by only copying bits stored on
the stack; no arbitrary code is necessary. See the “Stack-Only Data:
Copy” section in Chapter 4 for more
information on Copy
.
The Copy
trait doesn’t define any methods to prevent programmers from
overloading those methods and violating the assumption that no arbitrary code
is being run. That way, all programmers can assume that copying a value will be
very fast.
You can derive Copy
on any type whose parts all implement Copy
. A type that
implements Copy
must also implement Clone
, because a type that implements
Copy
has a trivial implementation of Clone
that performs the same task as
Copy
.
The Copy
trait is rarely required; types that implement Copy
have
optimizations available, meaning you don’t have to call clone
, which makes
the code more concise.
Everything possible with Copy
you can also accomplish with Clone
, but the
code might be slower or have to use clone
in places.
Hash
for Mapping a Value to a Value of Fixed Size
The Hash
trait allows you to take an instance of a type of arbitrary size and
map that instance to a value of fixed size using a hash function. Deriving
Hash
implements the hash
method. The derived implementation of the hash
method combines the result of calling hash
on each of the parts of the type,
meaning all fields or values must also implement Hash
to derive Hash
.
An example of when Hash
is required is in storing keys in a HashMap<K, V>
to store data efficiently.
Default
for Default Values
The Default
trait allows you to create a default value for a type. Deriving
Default
implements the default
function. The derived implementation of the
default
function calls the default
function on each part of the type,
meaning all fields or values in the type must also implement Default
to
derive Default
.
The Default::default
function is commonly used in combination with the struct
update syntax discussed in the “Creating Instances From Other Instances With
Struct Update
Syntax”
section in Chapter 5. You can customize a few fields of a struct and then
set and use a default value for the rest of the fields by using
..Default::default()
.
The Default
trait is required when you use the method unwrap_or_default
on
Option<T>
instances, for example. If the Option<T>
is None
, the method
unwrap_or_default
will return the result of Default::default
for the type
T
stored in the Option<T>
.
Appendix D - Useful Development Tools
In this appendix, we talk about some useful development tools that the Rust project provides. We’ll look at automatic formatting, quick ways to apply warning fixes, a linter, and integrating with IDEs.
Automatic Formatting with rustfmt
The rustfmt
tool reformats your code according to the community code style.
Many collaborative projects use rustfmt
to prevent arguments about which
style to use when writing Rust: everyone formats their code using the tool.
To install rustfmt
, enter the following:
$ rustup component add rustfmt
This command gives you rustfmt
and cargo-fmt
, similar to how Rust gives you
both rustc
and cargo
. To format any Cargo project, enter the following:
$ cargo fmt
Running this command reformats all the Rust code in the current crate. This
should only change the code style, not the code semantics. For more information
on rustfmt
, see its documentation.
Fix Your Code with rustfix
The rustfix tool is included with Rust installations and can automatically fix compiler warnings that have a clear way to correct the problem that’s likely what you want. It’s likely you’ve seen compiler warnings before. For example, consider this code:
Filename: src/main.rs
fn do_something() {} fn main() { for i in 0..100 { do_something(); } }
Here, we’re calling the do_something
function 100 times, but we never use the
variable i
in the body of the for
loop. Rust warns us about that:
$ cargo build
Compiling myprogram v0.1.0 (file:///projects/myprogram)
warning: unused variable: `i`
--> src/main.rs:4:9
|
4 | for i in 0..100 {
| ^ help: consider using `_i` instead
|
= note: #[warn(unused_variables)] on by default
Finished dev [unoptimized + debuginfo] target(s) in 0.50s
The warning suggests that we use _i
as a name instead: the underscore
indicates that we intend for this variable to be unused. We can automatically
apply that suggestion using the rustfix
tool by running the command cargo fix
:
$ cargo fix
Checking myprogram v0.1.0 (file:///projects/myprogram)
Fixing src/main.rs (1 fix)
Finished dev [unoptimized + debuginfo] target(s) in 0.59s
When we look at src/main.rs again, we’ll see that cargo fix
has changed the
code:
Filename: src/main.rs
fn do_something() {} fn main() { for _i in 0..100 { do_something(); } }
The for
loop variable is now named _i
, and the warning no longer appears.
You can also use the cargo fix
command to transition your code between
different Rust editions. Editions are covered in Appendix E.
More Lints with Clippy
The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code.
To install Clippy, enter the following:
$ rustup component add clippy
To run Clippy’s lints on any Cargo project, enter the following:
$ cargo clippy
For example, say you write a program that uses an approximation of a mathematical constant, such as pi, as this program does:
Filename: src/main.rs
fn main() { let x = 3.1415; let r = 8.0; println!("the area of the circle is {}", x * r * r); }
Running cargo clippy
on this project results in this error:
error: approximate value of `f{32, 64}::consts::PI` found
--> src/main.rs:2:13
|
2 | let x = 3.1415;
| ^^^^^^
|
= note: `#[deny(clippy::approx_constant)]` on by default
= help: consider using the constant directly
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#approx_constant
This error lets you know that Rust already has a more precise PI
constant
defined, and that your program would be more correct if you used the constant
instead. You would then change your code to use the PI
constant. The
following code doesn’t result in any errors or warnings from Clippy:
Filename: src/main.rs
fn main() { let x = std::f64::consts::PI; let r = 8.0; println!("the area of the circle is {}", x * r * r); }
For more information on Clippy, see its documentation.
IDE Integration Using rust-analyzer
To help IDE integration, the Rust community recommends using
rust-analyzer
. This tool is a set of
compiler-centric utilities that speaks the Language Server Protocol, which is a specification for IDEs and programming languages to
communicate with each other. Different clients can use rust-analyzer
, such as
the Rust analyzer plug-in for Visual Studio Code.
Visit the rust-analyzer
project’s home page
for installation instructions, then install the language server support in your
particular IDE. Your IDE will gain abilities such as autocompletion, jump to
definition, and inline errors.
Appendix E - Editions
In Chapter 1, you saw that cargo new
adds a bit of metadata to your
Cargo.toml file about an edition. This appendix talks about what that means!
The Rust language and compiler have a six-week release cycle, meaning users get a constant stream of new features. Other programming languages release larger changes less often; Rust releases smaller updates more frequently. After a while, all of these tiny changes add up. But from release to release, it can be difficult to look back and say, “Wow, between Rust 1.10 and Rust 1.31, Rust has changed a lot!”
Every two or three years, the Rust team produces a new Rust edition. Each edition brings together the features that have landed into a clear package with fully updated documentation and tooling. New editions ship as part of the usual six-week release process.
Editions serve different purposes for different people:
- For active Rust users, a new edition brings together incremental changes into an easy-to-understand package.
- For non-users, a new edition signals that some major advancements have landed, which might make Rust worth another look.
- For those developing Rust, a new edition provides a rallying point for the project as a whole.
At the time of this writing, three Rust editions are available: Rust 2015, Rust 2018, and Rust 2021. This book is written using Rust 2021 edition idioms.
The edition
key in Cargo.toml indicates which edition the compiler should
use for your code. If the key doesn’t exist, Rust uses 2015
as the edition
value for backward compatibility reasons.
Each project can opt in to an edition other than the default 2015 edition. Editions can contain incompatible changes, such as including a new keyword that conflicts with identifiers in code. However, unless you opt in to those changes, your code will continue to compile even as you upgrade the Rust compiler version you use.
All Rust compiler versions support any edition that existed prior to that compiler’s release, and they can link crates of any supported editions together. Edition changes only affect the way the compiler initially parses code. Therefore, if you’re using Rust 2015 and one of your dependencies uses Rust 2018, your project will compile and be able to use that dependency. The opposite situation, where your project uses Rust 2018 and a dependency uses Rust 2015, works as well.
To be clear: most features will be available on all editions. Developers using any Rust edition will continue to see improvements as new stable releases are made. However, in some cases, mainly when new keywords are added, some new features might only be available in later editions. You will need to switch editions if you want to take advantage of such features.
For more details, the Edition
Guide is a complete book
about editions that enumerates the differences between editions and explains
how to automatically upgrade your code to a new edition via cargo fix
.
Appendix F: Translations of the Book
For resources in languages other than English. Most are still in progress; see the Translations label to help or let us know about a new translation!
- Português (BR)
- Português (PT)
- 简体中文
- 正體中文
- Українська
- Español, alternate
- Italiano
- Русский
- 한국어
- 日本語
- Français
- Polski
- Cebuano
- Tagalog
- Esperanto
- ελληνική
- Svenska
- Farsi
- Deutsch
- हिंदी
- ไทย
- Danske
Appendix G - How Rust is Made and “Nightly Rust”
This appendix is about how Rust is made and how that affects you as a Rust developer.
Stability Without Stagnation
As a language, Rust cares a lot about the stability of your code. We want Rust to be a rock-solid foundation you can build on, and if things were constantly changing, that would be impossible. At the same time, if we can’t experiment with new features, we may not find out important flaws until after their release, when we can no longer change things.
Our solution to this problem is what we call “stability without stagnation”, and our guiding principle is this: you should never have to fear upgrading to a new version of stable Rust. Each upgrade should be painless, but should also bring you new features, fewer bugs, and faster compile times.
Choo, Choo! Release Channels and Riding the Trains
Rust development operates on a train schedule. That is, all development is
done on the master
branch of the Rust repository. Releases follow a software
release train model, which has been used by Cisco IOS and other software
projects. There are three release channels for Rust:
- Nightly
- Beta
- Stable
Most Rust developers primarily use the stable channel, but those who want to try out experimental new features may use nightly or beta.
Here’s an example of how the development and release process works: let’s
assume that the Rust team is working on the release of Rust 1.5. That release
happened in December of 2015, but it will provide us with realistic version
numbers. A new feature is added to Rust: a new commit lands on the master
branch. Each night, a new nightly version of Rust is produced. Every day is a
release day, and these releases are created by our release infrastructure
automatically. So as time passes, our releases look like this, once a night:
nightly: * - - * - - *
Every six weeks, it’s time to prepare a new release! The beta
branch of the
Rust repository branches off from the master
branch used by nightly. Now,
there are two releases:
nightly: * - - * - - *
|
beta: *
Most Rust users do not use beta releases actively, but test against beta in their CI system to help Rust discover possible regressions. In the meantime, there’s still a nightly release every night:
nightly: * - - * - - * - - * - - *
|
beta: *
Let’s say a regression is found. Good thing we had some time to test the beta
release before the regression snuck into a stable release! The fix is applied
to master
, so that nightly is fixed, and then the fix is backported to the
beta
branch, and a new release of beta is produced:
nightly: * - - * - - * - - * - - * - - *
|
beta: * - - - - - - - - *
Six weeks after the first beta was created, it’s time for a stable release! The
stable
branch is produced from the beta
branch:
nightly: * - - * - - * - - * - - * - - * - * - *
|
beta: * - - - - - - - - *
|
stable: *
Hooray! Rust 1.5 is done! However, we’ve forgotten one thing: because the six
weeks have gone by, we also need a new beta of the next version of Rust, 1.6.
So after stable
branches off of beta
, the next version of beta
branches
off of nightly
again:
nightly: * - - * - - * - - * - - * - - * - * - *
| |
beta: * - - - - - - - - * *
|
stable: *
This is called the “train model” because every six weeks, a release “leaves the station”, but still has to take a journey through the beta channel before it arrives as a stable release.
Rust releases every six weeks, like clockwork. If you know the date of one Rust release, you can know the date of the next one: it’s six weeks later. A nice aspect of having releases scheduled every six weeks is that the next train is coming soon. If a feature happens to miss a particular release, there’s no need to worry: another one is happening in a short time! This helps reduce pressure to sneak possibly unpolished features in close to the release deadline.
Thanks to this process, you can always check out the next build of Rust and
verify for yourself that it’s easy to upgrade to: if a beta release doesn’t
work as expected, you can report it to the team and get it fixed before the
next stable release happens! Breakage in a beta release is relatively rare, but
rustc
is still a piece of software, and bugs do exist.
Unstable Features
There’s one more catch with this release model: unstable features. Rust uses a
technique called “feature flags” to determine what features are enabled in a
given release. If a new feature is under active development, it lands on
master
, and therefore, in nightly, but behind a feature flag. If you, as a
user, wish to try out the work-in-progress feature, you can, but you must be
using a nightly release of Rust and annotate your source code with the
appropriate flag to opt in.
If you’re using a beta or stable release of Rust, you can’t use any feature flags. This is the key that allows us to get practical use with new features before we declare them stable forever. Those who wish to opt into the bleeding edge can do so, and those who want a rock-solid experience can stick with stable and know that their code won’t break. Stability without stagnation.
This book only contains information about stable features, as in-progress features are still changing, and surely they’ll be different between when this book was written and when they get enabled in stable builds. You can find documentation for nightly-only features online.
Rustup and the Role of Rust Nightly
Rustup makes it easy to change between different release channels of Rust, on a global or per-project basis. By default, you’ll have stable Rust installed. To install nightly, for example:
$ rustup toolchain install nightly
You can see all of the toolchains (releases of Rust and associated
components) you have installed with rustup
as well. Here’s an example on one
of your authors’ Windows computer:
> rustup toolchain list
stable-x86_64-pc-windows-msvc (default)
beta-x86_64-pc-windows-msvc
nightly-x86_64-pc-windows-msvc
As you can see, the stable toolchain is the default. Most Rust users use stable
most of the time. You might want to use stable most of the time, but use
nightly on a specific project, because you care about a cutting-edge feature.
To do so, you can use rustup override
in that project’s directory to set the
nightly toolchain as the one rustup
should use when you’re in that directory:
$ cd ~/projects/needs-nightly
$ rustup override set nightly
Now, every time you call rustc
or cargo
inside of
~/projects/needs-nightly, rustup
will make sure that you are using nightly
Rust, rather than your default of stable Rust. This comes in handy when you
have a lot of Rust projects!
The RFC Process and Teams
So how do you learn about these new features? Rust’s development model follows a Request For Comments (RFC) process. If you’d like an improvement in Rust, you can write up a proposal, called an RFC.
Anyone can write RFCs to improve Rust, and the proposals are reviewed and discussed by the Rust team, which is comprised of many topic subteams. There’s a full list of the teams on Rust’s website, which includes teams for each area of the project: language design, compiler implementation, infrastructure, documentation, and more. The appropriate team reads the proposal and the comments, writes some comments of their own, and eventually, there’s consensus to accept or reject the feature.
If the feature is accepted, an issue is opened on the Rust repository, and
someone can implement it. The person who implements it very well may not be the
person who proposed the feature in the first place! When the implementation is
ready, it lands on the master
branch behind a feature gate, as we discussed
in the “Unstable Features” section.
After some time, once Rust developers who use nightly releases have been able to try out the new feature, team members will discuss the feature, how it’s worked out on nightly, and decide if it should make it into stable Rust or not. If the decision is to move forward, the feature gate is removed, and the feature is now considered stable! It rides the trains into a new stable release of Rust.