Język Programowania Rust

autorstwa Steve Klabnik i Carol Nichols, ze wsparciem społeczności Rusta

Bieżąca wersja tekstu zakłada, że używasz Rusta w wersji 1.67.1 (wydanego 2023-02-09) lub nowszego. Zajrzyj do sekcji "Instalacja" w rozdziale 1 celem uzyskania informacji o sposobach instalacji lub aktualizacji Rusta.

Oryginalna, anglojęzyczna wersja książki w wersji HTML dostępna jest na stronie https://doc.rust-lang.org/stable/book/ oraz w trybie offline, instalowana wraz z Rustem przy użyciu rustup. Użyj polecenia rustup docs --book, żeby ją otworzyć.

Istnieje kilka społecznościowych [tłumaczeń] tej książki. Niniejsze tłumaczenie jest zaś dostępna na stronie http://rust.w8.pl/book/.

Anglojęzyczna wersja dostępna jest też w wersji papierowej oraz ebooka za sprawą wydawnictwa No Starch Press.

🚨 Want a more interactive learning experience? Try out a different version of the Rust Book, featuring: quizzes, highlighting, visualizations, and more: https://rust-book.cs.brown.edu

Przedmowa

To nie zawsze było oczywiste, ale rolą języka programowania Rust fundamentalnie jest potęgowanie możliwości: nieważne, jaki kod aktualnie piszesz, Rust pozwala ci sięgać dalej i pewnie programować w szerszym zakresie domen niż kiedykolwiek wcześniej.

Spójrz przykładowo na pracę na „poziomie systemowym”, gdzie trzeba borykać się z takimi niskopoziomowymi szczegółami jak zarządzanie pamięcią, reprezentacja danych czy współbieżność. Tradycyjnie, ten obszar programowania był postrzegany jako tajemny i dostępny jedynie dla wybranej garstki, która poświęciła długie lata, by nauczyć się unikać jego osławionych pułapek. Nawet ci, którzy się tym zajmują, robią to uważnie, aby ich kod nie stał się furtką dla exploitów, awarii lub innych przykładów zepsucia.

Rust pozbywa się tych barier poprzez eliminację starych zasadzek i dostarczenie przyjaznego i dopracowanego zestawu narzędzi, które pomagają ci po drodze. Programiści zmuszeni do „umoczenia się” w niskopoziomowej kontroli, mogą do tego celu użyć Rusta, bez podejmowania zwyczajowego ryzyka wywołania awarii lub dziur bezpieczeństwa i bez konieczności uczenia się drobnych szczegółów kapryśnych narzędzi. Nawet lepiej, język zaprojektowano z myślą o prowadzeniu cię w sposób naturalny ku tworzeniu niezawodnego kodu, który jest wydajny zarówno pod względem szybkości, jak i wykorzystania pamięci.

Programiści, którzy już pracują z niskopoziomowym kodem, mogą użyć Rusta do podniesienia swoich ambicji. Dla przykładu, wprowadzenie wielowątkowości w Ruście jest mało ryzykowną operacją: kompilator wyłapie za ciebie popularne błędy. Możesz też uderzyć w bardziej agresywną optymalizację kodu z uczuciem pewności, że nie wprowadzisz przypadkowo źródeł awarii czy podatności na ataki.

Ale Rust nie jest ograniczony do programowania systemowego i niskopoziomowego. Jest ekspresyjny i wystarczająco ergonomiczny, żeby za jego pomocą tworzyć aplikacje CLI, serwery sieciowe i wiele innych rodzajów przyjaznego do pisania kodu - w dalszej części książki znajdziesz proste przykłady obu takich programów. Praca z Rustem pozwala ci na budowanie umiejętności, które można przenosic z jednej domeny do drugiej; możesz uczyć sie Rusta pisząc aplikację sieciową, by potem zastosować te same rozwiązania tworząc dla Raspberry Pi.

Niniejsza książka w pełni obejmuje potencjał Rusta do ulepszania swoich użytkowników. To przyjazny i dostępny tekst, nakierowany nie tylko na pomoc w podniesieniu twojego poziomu znajomości Rusta, ale również na poprawę twojej pewności siebie jako programisty w ujęciu ogólnym. Zanurz się więc, przygotuj na naukę - i witaj w społeczności Rusta!

— Nicholas Matsakis i Aaron Turon

Wstęp

Uwaga: Niniejsze tłumaczenie oparto na wydaniu książki The Rust Programming Language dostępnej w druku oraz w wersji elektronicznej, wydanych przez No Starch Press.

Witaj na łamach Języka Programowania Rust - wprowadzającej ksiażki o Ruście. Język programowania Rust pomaga w tworzeniu szybszego, bardziej niezawodnego oprogramowania. Konstrukcja języków stawia często wysokopoziomową ergonomię w bezpośrednim konflikcie z niskopoziomowym stopniem kontroli. Rust rzuca wyzwanie temu problemowi. Dzięki zrównoważeniu potężnych możliwości technicznych i świetnego doświadczenia dla programistów, Rust daje szansę objęcia kontroli nad niskopoziomowymi szczegółami (takimi jak zarządzanie pamięcią) bez napotykania na problemy, które tradycyjnie takiej możliwości towarzyszyły.

Dla kogo jest Rust

Rust jest idealnym wyborem dla wielu ludzi z wielu różnych powodów. Przyjrzyjmy się kilku najważniejszym grupom.

Zespoły deweloperów

Rust dowodzi swojej produktywności jako narzędzie kolaboracji wśród dużych zespołów deweloperów, ze zróżnicowaną wiedzą na temat programowania systemowego. Niskopoziomowy kod jest podatny na rozmaite, subtelne błędy (bugi), które w większości innych języków programowania da się wyłapać jedynie poprzez rozległe testy i ostrożne sprawdzanie kodu przez doświadczonych programistów. W Ruście kompilator pełni rolę bramkarza, który nie dopuszcza do skompilowania kodu zawiarającego tego typu błędy. Dotyczy to również błędów w programach współbieżnych (wielowątkowych). Współpraca z kompilatorem pozwala zespołowi spędzić więcej czasu na dopracowywaniu logiki programu niż na polowaniu na bugi.

Rust jednocześnie wnosi do świata programowania systemowego nowoczesne narzędzia deweloperskie:

  • Cargo - dołączony menedżer zależności i narzędzie do budowania, czyni dodawanie, kompilowanie i zarządzanie zależnościami bezbolesnym i spójnym procesem w obrębie ekosystemu Rusta.
  • Rustfmt zapewnia spójny styl kodu wśród deweloperów.
  • Serwer języka Rust (Rust Language Server) zapewnia w konkretnych Zintegrowanych Środowiskach Programistycznych (IDE) auto-uzupełnianie oraz ostrzeżenia inline o błędach.

Korzystając z tych oraz innych narzędzi w ekosystemie Rusta, deweloperzy mogą pozostać produktywni również podczas pisania kodu niskopoziomowego.

Uczniowie

Rust jest językiem dla uczniów i osób zainteresowanych uczeniem się systemowych pojęć. Z pomocą Rusta, wielu ludzi poznało tematy z zakresu rozwoju systemów operacyjnych. Społeczność Rusta jest niezwykle gościnna i chętnie odpowiada na pytania uczniów. Poprzez zaangażowanie w projekty takie jak niniejsza książka, zespoły tworzące Rusta chcą uczynić pojęcia systemowe osiągalnymi dla większej ilości osób, szczególnie tych, dla których programowanie jest czymś zupełnie nowym.

Firmy

W setkach dużych i małych firm używa się Rusta do różnych zadań, w poczet których można zaliczyć: narzędzia linii poleceń, usługi sieciowe, narzędzia w DevOps, urządzenia wbudowane, analizę i przetwarzanie audio i video, kryptowaluty, bioinformatykę, silniki wyszukiwarek, aplikacje w Internecie Rzeczy, uczenie maszynowe, a nawet główne komponenty przeglądarki sieciowej Firefox.

Programiści open source

Rust jest dla tych, którzy chcą tworzyć również sam język Rust, jego społeczność, narzędzia deweloperskie oraz biblioteki. Z przyjemnością ujrzelibyśmy Twój wkład w tworzenie Rusta.

Ludzie, którzy cenią szybkość i stabilność

Rust powstał dla ludzi, którzy poszukują w języku programowania szybkości i stabilności. Przez szybkość rozumiemy zarówno szybkość działania programów napisanych w Ruście, jak i oferowaną przez ten język szybkość ich pisania. Weryfikacje przez kompilator Rusta zapewniają stabilność programu podczas refaktorowania i dodawania nowych funkcjonalności. Kontrastuje to z kruchym, zaległym kodem, którego deweloperzy często boją się modyfikować, co ma miejsce w językach pozbawionych podobnych mechanizmów kontroli. Dążąc do wykorzystania bezkosztowych abstrakcji oraz wysokopoziomowych rozwiązań, które kompilują się do kodu niskopoziomowego równie szybkiego, co ten pisany ręcznie, Rust stara się, aby bezpieczny kod mógł być jednocześnie szybki.

Twórcy Rusta mają nadzieję wspierać również wielu innych użytkowników. Wymienieni stanowią jedynie kilkoro z największych interesariuszy. Ogólnie rzecz ujmując, największą aspiracją Rusta jest wyeliminowanie kompromisów, które programiści zaakceptowali w ciągu dekad, poprzez zaoferowanie jednocześnie: bezpieczeństwa i produktywności, szybkości oraz ergonomii. Wypróbuj Rusta i sprawdź, czy i tobie pasują jego wybory.

Dla kogo jest ta książka

Niniejsza książka zakłada, że czytelnik pisał już kod w innym języku, ale nie określa w żaden sposób, w jakim. Starano się dostarczyć materiał szeroko dostępny dla osób o wysoce zróżnicowanych podstawach w programowaniu. Nie poświęcono wiele czasu tłumaczeniu, czym jest programowanie lub jak o nim myśleć. Jeżeli jesteś osobą zupełnie nową w temacie programowania, większe korzyści przyniesie ci przeczytanie innych pozycji, wprowadzających do programowania.

Jak używać tej książki

Głównym założeniem w książce jest to, że jest ona czytana kolejno, od początku do końca. Późniejsze rozdziały opierają się na pojęciach z rozdziałów wcześniejszych, a te z kolei mogą nie wchodzić w niektóre szczegóły omawianego tematu. Do wielu tematów wracamy zazwyczaj w późniejszych rozdziałach.

W książce znajdują się rozdziały dwojakie: pojęciowe i projektowe. W rozdziałach pojęciowych zapoznasz się z aspektami Rusta, a w rozdziałach projektowych stworzymy razem krótkie programy wykorzystujące wiedzę przekazaną do danego momentu. Rozdziałami projektowymi są te o numerach 2, 12 i 20. Pozostałe to rozdziały pojęciowe.

Rozdział 1 wyjaśnia, jak zainstalować Rusta, jak napisać program „Witaj, świecie!” oraz jak używać Cargo - menedżera pakietów i narzędzie budowania Rusta. Rozdział 2 jest praktycznym wprowadzeniem do języka Rust. Poszczególne pojęcia omawiamy tu ogólnie, podczas gdy szczegóły zostaną wyjaśnione w późniejszych rozdziałach. Jeżeli chcesz od razu pobrudzić sobie ręce, rozdział 2 jest do tego idealnym miejscem. W rozdziale 3 omawiane są funkcje języka Rust podobne do tych z innych języków programowania. Z rozdziału 4 można nauczyć się systemu własności w Ruście. Jeśli jednak należysz do szczególnie skrupulatnych czytelników, którzy wolą poznać każdy szczegół przed przejściem do kolejnych tematów, możesz wstępnie pominąć rozdział 2 i przejść prosto do rozdziału 3, po czym cofać się do rozdziału 2 dopiero, gdy zechcesz wykorzystać w opisanym tam projekcie rzeczy, których się nauczyłeś.

Rozdział 5 omawia struktury i metody, a rozdział 6 obejmuje typy wyliczeniowe enum, wyrażenia match oraz konstrukcję if let. Struktury i typy wyliczeniowe stosowane są w Ruście do tworzenia własnych typów.

W rozdziale 7 dowiadujemy się o systemie modułów w Ruście oraz o zasadach prywatności przy organizacji kodu oraz jego publicznego Interfejsu Programowania Aplikacji (API). Rozdział 8 omawia niektóre popularne struktury danych kolekcji dostarczone przez bibliotekę standardową, takie jak wektory, ciągi znaków (string) i tablice mieszające (hash map). Rozdział 9 odkrywa filozofię oraz techniki obsługi błędów w Ruście.

Rozdział 10 wchodzi w temat typów ogólnych, cech (traits) oraz trwałości (lifetimes), które dają ci możliwość definiowania kodu, odnoszącego się do wielu typów danych. Rozdział 11 jest w całości poświęcony testowaniu, które mimo gwarancji bezpieczeństwa Rusta nadal jest konieczne, by zapewnić prawidłową logikę wykonywania programów. W rozdziale 12 budujemy natomiast własną implementację fragmentu funkcjonalności polecenia grep, które wyszukuje tekst w treści plików. Do tego celu będzie potrzebny cały szereg pojęć omówionych w poprzednich rozdziałach.

Rozdział 13 omawia domknięcia (closures) oraz iteratory: cechy Rusta wywodzące się z języków funkcyjnych. W rozdziale 14 głębiej przyglądamy się Cargo i mówimy o najlepszych praktykach dotyczących dzielenia się swoimi bibliotekami z innymi programistami. Rozdział 15 omawia dostarczone w bibliotece standardowej inteligentne wskaźniki oraz cechy, które zapewniają im funkcjonalność.

W rozdziale 16 przechodzimy przez różne modele programowania współbieżnego oraz tłumaczymy, jak Rust pomaga w programowaniu wielowątkowym bez obaw. Rozdział 17 wyjaśnia z kolei, jak idiomy Rusta można porównać do zasad programowania obiektowego, z którym możesz być już zaznajomiony.

Rozdział 18 omawia wzorce oraz dopasowywanie wzorców, co jest potężnym narzędzie do wyrażania myśli w programach pisanych w Ruście. Rozdział 19 jest swoistym tyglem ciekawszych, zaawansowanych tematów, wliczając niebezpiecznego Rusta i więcej na temat trwałości, cech, typów, funkcji i domknięć.

W rozdziale 20 tworzymy projekt, w którym implementujemy wielowątkowy, niskopoziomowy serwer sieciowy!

Na zakończenie, kilka dodatków zawiera przydatne informacje o języku w formacie przypominajacym książkę referencyjną. Dodatek A obejmuje słowa kluczowe Rusta, Dodatek B operatory i symbole, Dodatek C omawia dostarczone przez bibliotekę standardową cechy wyprowadzane, natomiast Dodatek D - kilka przydatnych narzędzi deweloperskich, a Dodatek E wyjaśnia koncepcję edycji Rusta. W dodatku F można znaleźć tłumaczenia książki, a w dodatku G zajmiemy się tym, jak powstaje Rust i czym jest Rust Nightly.

Nie ma złego sposobu na czytanie tej ksiażki - jeśli masz ochotę skakać w przód, proszę bardzo! Powrót do wcześniejszych rozdziałów może okazać się konieczny, jeżeli doświadczysz uczucia zagubienia. Rób wszystko, co ci pomaga.

Ważną częścią procesu poznawania Rusta jest uczenie się odczytywania komunikatów błędów wyświetlanych przez kompilator: będą cię one nakierowywać na uzyskanie działającego kodu. Dlatego też zaprezentujemy wiele przykładów kodu, który się nie kompiluje, wraz z komunikatami błędów zwracanych w każdym przypadku przez kompilator. Miej świadomość, że wybrany przez ciebie na chybił-trafił przykład może się nie skompilować. Koniecznie przeczytaj okalający go tekst aby sprawdzić, czy dany kod przy próbie kompilacji powinien zwrócić błąd. Również Ferris pomoże ci rozpoznać kod, który nie powinien zadziałać:

FerrisZnaczenie
Ferris with a question markTen kod się nie kompiluje!
Ferris throwing up their handsTen kod panikuje!
Ferris with one claw up, shruggingTen kod nie daje pożądanego zachowania.

W większości przypadków pokierujemy cię do uzykania prawidłowej wersji kodu, który pierwotnie się nie kompiluje.

Kod źródłowy

Pliki źródłowe, z których wygenerowana została niniejsza książka, można znaleźć na GitHubie.

Informacje od tłumaczy

W niniejszej książce znajdziesz wiele przykładów programów oraz wycinki kodu, w których: łańcuchy znaków w makrach println!, komentarze, a czasem nawet nazwy projektów Cargo; zostały przetłumaczone. Jest to zabieg tłumaczy mający na celu jak największe usunięcie bariery jaką stwarza użycie języka angielskiego w zrozumieniu pojęć zawartych w tej książce. Prosimy, abyś rozważył(a) użycie języka angielskiego, kiedy zdecydujesz się na udostępnienie swojego kodu, zarówno w przypadku Rusta przy udostępnianiu własnych skrzyń, jak i w przypadku wszelkich innych języków programowania.

Na początek

Zacznijmy twoją podróż z Rustem! Jest wiele do nauczenia, ale każda podróż ma gdzieś swój początek. W tym rozdziale omówimy:

  • Instalację Rusta pod Linuksem, macOS i Windowsem
  • Stworzenie programu wyświetlającego tekst „Witaj, świecie!”
  • Używanie cargo, menadżera pakietów i systemu budowania Rusta

Instalacja

Naszym pierwszym krokiem jest zainstalowanie Rusta. Ściągniemy go za pomocą rustup, narzędzia uruchamianego z linii poleceń, które służy do zarządzania wersjami Rusta i powiązanych narzędzi. Będzie do tego potrzebne połączenie z internetem.

Uwaga: Jeśli z jakiegoś powodu wolisz nie używać narzędzia rustup, odwiedź Stronę opisującą inne metody instalacji Rusta.

Wykonanie kolejnych kroków spowoduje zainstalowanie najnowszej, stabilnej wersji kompilatora Rusta. Stabilność Rusta gwarantuje, że wszystkie przykłady z książki, które poprawnie się kompilują, kompilowały się będą nadal w nowszych wersjach języka. Komunikaty zwrotne błędów i ostrzeżeń mogą nieco różnić się od siebie w zależności od wersji, ponieważ dość często są one poprawiane. Innymi słowy, każda nowsza, stabilna wersja Rusta zainstalowana przy użyciu tych samych kroków powinna współgrać z treścią książki zgodnie z oczekiwaniami.

Oznaczenia w linii poleceń

W tym rozdziale oraz w dalszych częściach książki, będziemy korzystać z poleceń wydawanych przy użyciu terminala. Wszystkie linie, które powinno się wprowadzić w terminalu będą rozpoczynać się od znaku $. Nie musisz go wpisywać. Pokazany jest on jedynie celem zidentyfikowania początku każdego polecenia. Linie, które nie zaczynają się od $, zazwyczaj pokazują komunikat wyświetlony po wydaniu ostatniego polecenia. Dodatkowo, specyficzne przykłady dla terminala PowerShell będą wykorzystywały znak > zamiast $.

Instalacja rustup pod Linuksem lub macOS

Jeśli korzystasz z Linuksa lub macOS, otwórz konsolę / terminal i wpisz następujące polecenie:

$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

Spowoduje to ściągnięcie skryptu, który rozpocznie instalację narzędzia rustup, które z kolei zainstaluje najnowszą, stabilną wersję Rusta. Możesz otrzymać prośbę o wprowadzenie swojego hasła. Jeśli wszystko się powiedzie, zobaczysz na ekranie taki tekst:

Rust is installed now. Great!

Będziesz też potrzebować programu linkującego (linkera), którego Rust używa do złączenia wyników kompilowania w jeden plik. Prawdopodobnie masz już taki zainstalowany, ale jeżeli przy próbie kompilacji programu Rusta uzyskasz błędy informujące, że nie można uruchomić linkera, oznacza to, że w danym systemie linker nie jest zainstalowany i konieczna jest jego ręczna instalacja. Kompilatory języka C zazwyczaj wyposażone są w odpowiedni linker. Sprawdź dokumentację swojej platformy, aby dowiedzieć się, jak przeprowadzić ewentualną instalację kompilatora C. Wiele popularnych pakietów Rusta korzysta z kodu C i wymaga również kompilatora C. Z tego względu jego instalacja w tym momencie może być zasadna.

On macOS, you can get a C compiler by running:

$ xcode-select --install

Linux users should generally install GCC or Clang, according to their distribution’s documentation. For example, if you use Ubuntu, you can install the build-essential package.

Instalacja rustup pod Windowsem

Z poziomu Windowsa, odwiedź stronę https://www.rust-lang.org/tools/install i kieruj się instrukcjami instalacji Rusta. W którymś momencie procesu otrzymasz komunikat informujący, że będziesz również potrzebować narzędzi budowania MSVC dla Visual Studio 2013 lub nowszego.

To acquire the build tools, you’ll need to install Visual Studio 2022. When asked which workloads to install, include:

  • „Desktop Development with C++”
  • The Windows 10 or 11 SDK
  • The English language pack component, along with any other language pack of your choosing

Dalsza część książki będzie zawierać polecenia działające zarówno w cmd.exe jak i w PowerShell. Jeżeli pojawią się jakieś różnice, zostaną one wyjaśnione.

Aktualizowanie i odinstalowanie

Kiedy już zainstalujesz Rusta używając rustup, aktualizacja do najnowszej wersji jest prosta. W terminalu uruchom następujący skrypt aktualizacji:

$ rustup update

Aby odinstalować Rusta oraz rustup, w terminalu uruchom skrypt dezinstalacji:

$ rustup self uninstall

Rozwiązywanie problemów

Aby sprawdzić, czy Rust jest prawidłowo zainstalowany, otwórz terminal i wpisz następujące polecenie:

$ rustc --version

Powinien się wyświetlić numer wersji, hasz oraz data commita najnowszej wersji stabilnej, w formacie podobnym do poniższego:

rustc x.y.z (abcabcabc rrrr-mm-dd)

Jeśli widzisz coś takiego, Rust zainstalował się prawidłowo! Jeśli nie, to sprawdź czy Rust został dodany do zmiennej środowiskowej %PATH%.

In Windows CMD, use:

> echo %PATH%

In PowerShell, use:

> echo $env:Path

In Linux and macOS, use:

$ echo $PATH

If that’s all correct and Rust still isn’t working, there are a number of places you can get help. Find out how to get in touch with other Rustaceans (a silly nickname we call ourselves) on the community page.

Lokalna dokumentacja

Instalacja dołącza również lokalną kopię dokumentacji, więc można ją czytać offline. Uruchom rustup doc, żeby otworzyć lokalną dokumentację w swojej przeglądarce.

Za każdym razem, kiedy przytoczone są typ lub funkcja z biblioteki standardowej, a nie masz pewności co robią lub jak ich użyć, użyj dokumentacji API (Interfejs Programowania Aplikacji), aby się dowiedzieć.

Witaj, świecie!

Ponieważ Rust jest już zainstalowany, napiszmy pierwszy program. Przy poznawaniu nowego języka tradycją stało się tworzenie krótkiego programu, który wyświetla na ekranie tekst „Witaj, świecie! (ang. „Hello World!”). Postąpimy tu tak samo.

Uwaga: Książka zakłada u czytelnika podstawową znajomość wiersza poleceń. Sam Rust nie wymaga konkretnego edytora, narzędzi czy też miejsca, gdzie zapisany jest kod, więc jeśli preferujesz używanie zintegrowanego środowiska programistycznego zamiast wiersza poleceń, masz do tego pełne prawo. Wiele IDE obsługuje Rusta w pewnym stopniu - możesz sprawdzić dokumentację swojego IDE, aby uzyskać szczegóły. Zespół Rusta ostatnio zadbał o obsługę języka w niektórych IDE dzięki rust-analyzer. Więcej szczegółów zawiera Dodatek D.

Tworzenie katalogu projektu

W pierwszej kolejności utwórz katalog, w którym umieścisz swój kod. Rust w żaden sposób nie narzuca lokalizacji dla kodu, ale dla potrzeb niniejszej książki sugerujemy utworzenie katalogu projects w katalogu domowym i przechowywanie tam wszystkich swoich programów.

Otwórz terminal i wprowadź następujące polecenia, aby utworzyć katalog projects, w którym umieścimy kolejny, pod projekt „Witaj, świecie!”:

Pod Linuksem, macOS, lub w PowerShell pod Windowsem, wpisz to:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world

W Windows CMD, wpisz to:

> mkdir %USERPROFILE%\projects
> cd /d %USERPROFILE%\projects
> mkdir hello_world
> cd hello_world

Pisanie i uruchamianie programu w Ruście

Następnie utwórz nowy plik źródłowy i nazwij go main.rs. Pliki języka Rust zawsze zakończone są rozszerzeniem .rs. Jeśli w nazwie pliku znajduje się więcej niż jedno słowo, użyj znaku podkreślenia jako separatora. Na przykład, hello_world.rs zamiast helloworld.rs.

Otwórz plik main.rs, który właśnie utworzyłeś i wprowadź kod podany w Listingu 1-1:

Plik: main.rs

fn main() {
    println!("Witaj, świecie!");
}

Listing 1-1: Program wyświetlający „Witaj, świecie!”

Zapisz plik i wróć do okna terminala w katalogu ~/projects/hello_world. Pod Linuksem lub macOS, wprowadź podane polecenia, żeby skompilować i uruchomić program:

$ rustc main.rs
$ ./main
Witaj, świecie!

Pod Windowsem, uruchom .\main.exe zamiast ./main.

> rustc main.rs
> .\main.exe
Witaj, świecie!

Bez względu na posiadany system operacyjny, powinieneś/powinnaś zobaczyć w oknie terminala wyświetlony tekst Witaj, świecie!. Jeśli nic takiego nie widzisz, zajrzyj do sekcji „Rozwiązywanie problemów” w rozdziale poświęconym instalacji, po sposoby na otrzymanie pomocy.

Jeśli widzisz tekst Witaj, świecie!, to gratulacje! Właśnie oficjalnie napisałeś program w Ruście, a to czyni z ciebie programistę Rusta - Witaj!

Anatomia programu w Ruście

Przyjrzyjmy się teraz dokładnie, co właściwie dzieje się w twoim programie „Witaj, świecie!”. Oto pierwsza część układanki:

fn main() {

}

Powyższe linie definiują w Ruście funkcję. Funkcja main jest szczególna: to pierwsza rzecz, która wykonuje się w każdym programie napisanym w Ruście. Pierwsza linia deklaruje funkcję o nazwie main, która nie przyjmuje argumentów oraz niczego nie zwraca. Gdyby funkcja przyjmowała jakieś argumenty, ich nazwy umieszczone byłyby w nawiasach, ().

Zwróć też uwagę, że ciało funkcji otoczone jest nawiasami klamrowymi, {}. Rust wymaga tych znaków wokół ciał wszystkich funkcji. Za dobry styl uważa się umieszczenie klamry otwierającej w tej samej linii, co deklaracja funkcji i oddzielenie jej od poprzedzającego kodu jedną spacją.

Uwaga: Jeśli chcesz trzymać się ściśle standardowego stylu używanego w Rustowych projektach, możesz użyć rustfmt -- narzędzia do automatycznego formatowania kodu do konkretnego stylu (więcej o rustfmt jest w Dodatku D). Programu zawarty jest w standardowej dystrybucji Rusta, tak jak rustc, więc rustfmt prawdopodobnie już zainstalowany na twoim komputerze!

Wewnątrz funkcji main mamy następujący kod:

#![allow(unused)]
fn main() {
    println!("Witaj, świecie!");
}

Ta linia wykonuje całą robotę w naszym krótkim programie: wyświetla tekst na ekranie. Należy tu zwrócić uwagę na cztery szczegóły.

Po pierwsze, wcięcie tekstu w Ruście składa się z czterech spacji, a nie z tabulatora.

Po drugie, println! wywołuje w Ruście makro. Gdyby wywoływana była funkcja, wpisana byłaby jako println (bez !). Makra będą szerzej opisane w rozdziale 19. Jedyne, co musisz wiedzieć teraz, to to, że użycie ! wywołuje makro zamiast zwykłej funkcji i że makra nie zawsze podlegają tym samym regułą co funkcje.

Po trzecie, w programie widzimy łańcuch znaków (string) "Witaj, świecie!". Przekazujemy go jako argument do println!, którego ostatecznym efektem jest wyświetlenie łańcucha na ekranie.

Po czwarte, linia zakończona jest średnikiem (;), który oznacza, że bieżące wyrażenie jest zakończone i można zacząć kolejne. Większość linii w Ruście kończy się znakiem średnika.

Kompilacja i uruchomienie to oddzielne kroki

Przed momentem uruchomiliśmy nowo napisany program. Zbadajmy teraz kolejno każdy poprzedzający ten moment etap.

Zanim uruchomisz program w Ruście, należy go skompilować kompilatorem Rusta, wprowadzając polecenie rustc i przekazując do niego jako argument nazwę pliku źródłowego. Wygląda to tak:

$ rustc main.rs

Jeśli masz doświadczenie w C lub C++, zauważysz, że jest to podobne do wywoływania gcc lub clang. Po udanej kompilacji, Rust tworzy binarny plik wykonywalny.

Pod Linuksem, macOS lub w PowerShell pod Windowsem możesz sprawdzić obecność pliku wykonywalnego używając w terminalu polecenia ls:

$ ls
main  main.rs

W przypadku Linuksa i macOS zobaczysz dwa pliki. PowerShell pod Windowsem wyświetli trzy pliki - te same, które wyświetliłby CMD. W CMD pod Windowsem możesz wpisać:

> dir /B %= opcja /B powoduje wyświetlenie jedynie nazw plików =%
main.exe
main.pdb
main.rs

To potwierdza obecność kodu źródłowego z rozszerzeniem .rs, programu wykonywalnego (main.exe pod Windowsem, main wszędzie indziej), a także, w przypadku Windowsa, pliku z rozszerzeniem .pdb zawierającego informacje debugujące. Wszystko, co pozostało do zrobienia, to uruchomienie pliku main lub main.exe, w taki sposób:

$ ./main # lub .\main.exe pod Windowsem

Jeżeli main.rs jest twoim programem „Witaj, świecie!”, wyświetli to w oknie terminala tekst Witaj, świecie!.

Jeśli jesteś doświadczony w językach dynamicznych, takich jak Ruby, Python lub JavaScript, możesz nie być przyzwyczajony do traktowania kompilacji i uruchomienia programu jako oddzielnych kroków. Rust jest językiem kompilowanym z wyprzedzeniem, co oznacza, że możesz skompilować program i dać go komuś, kto uruchomi go nawet nie mając zainstalowanego Rusta. Jeśli natomiast dasz komuś plik .rb, .py lub .js, odbiorca musi mieć zainstalowane odpowiednio implementacje Ruby, Pythona lub JavaScript. Jednak w tych językach jedna komenda wystarczy, aby jednocześnie skompilować i uruchomić program. Wszystko jest kompromisem w konstrukcji danego języka.

Kompilacja poprzez rustc jest wystarczająca dla prostych programów, ale w miarę rozrastania się twojego projektu, odczujesz potrzebę zarzadzania wszystkimi dostępnymi w nim opcjami i ułatwienia dzielenia się kodem. W dalszym ciągu przedstawimy narzędzie zwane Cargo, które pomoże ci w pisaniu prawdziwych programów w Ruście.

Witaj, Cargo!

Cargo jest menedżerem pakietów i systemem budowania Rusta. Większość Rustowców używa tego narzędzia do zarządzania swoimi projektami, ponieważ Cargo potrafi wykonać za nich wiele zadań, takich jak budowanie kodu oraz ściąganie i budowanie bibliotek, od których kod jest zależny. Biblioteki, których wymaga twój kod nazywamy zależnościami (dependencies).

Najprostsze programy w Ruście, takie jak ten, który właśnie napisaliśmy, nie mają żadnych zależności, więc gdybyśmy zbudowali projekt „Witaj, świecie!” (ang. „Hello World!”) za pomocą Cargo, zostałaby użyta tylko ta część narzędzia, która zajmuje się budowaniem kodu. W miarę pisania bardziej skomplikowanych programów, zechcesz dodawać zależności i jeśli swój projekt rozpoczniesz z użyciem Cargo, będzie to o wiele łatwiejsze do zrobienia.

Jako że przeważająca większość projektów w Ruście używa Cargo, w dalszym ciągu książki założymy, że ty również go używasz. Jeśli korzystałeś(-aś) z oficjalnych instalatorów, zgodnie z opisem w sekcji „Instalacja”, Cargo zainstalował się razem z Rustem. Jeżeli instalowałeś(-aś) Rusta w inny sposób, możesz sprawdzić, czy Cargo jest zainstalowany, przez wprowadzenie w terminalu następującej komendy:

$ cargo --version

Jeżeli widzisz numer wersji, Cargo jest zainstalowane! Jeśli natomiast pojawia się błąd z rodzaju komendy nie znaleziono, powinieneś/powinnaś zajrzeć do dokumentacji swojej metody instalacji celem ustalenia, jak zainstalować Cargo osobno.

Tworzenie projektu z Cargo

Stwórzmy nowy projekt z pomocą Cargo i przyjrzyjmy się, czym różni się on od naszego pierwotnego projektu „Witaj, świecie!”. Przejdź z powrotem do swojego katalogu projects (lub innego, w którym zdecydowałeś(-aś) się trzymać swój kod) i bez względu na posiadany system operacyjny wprowadź polecenie:

$ cargo new hello_cargo
$ cd hello_cargo

Pierwsze polecenie stworzy nowy katalog o nazwie hello_cargo. Ponieważ nadaliśmy naszemu projektowi nazwę hello_cargo, Cargo tworzy jego pliki źródłowe w katalogu o tej samej nazwie.

Wejdź do katalogu hello_cargo i wyświetl listę plików. Powinieneś(-aś) zobaczyć, że Cargo utworzył dla nas dwa pliki i jeden podkatalog: plik Cargo.toml oraz katalog src z plikiem main.rs wewnątrz. Zainicjował również nowe repozytorium Gita, w komplecie z plikiem .gitignore. Gdybyś jednak wykonał(a) komendę cargo new w folderze, w którym istnieje już repozytorium Gita, to pliki związane z Gitem nie zostałyby stworzone. Możesz zmienić to zachowanie używając komendy cargo new --vcs=git.

Uwaga: Git jest często stosowanym systemem kontroli wersji. Możesz zlecić cargo new zastosowanie innego systemu kontroli wersji lub też nie stosowanie żadnego, za pomocą flagi --vcs. Uruchom cargo new --help, żeby zobaczyć dostępne opcje.

Otwórz plik Cargo.toml w wybranym przez siebie edytorze tekstu. Zawartość powinna wyglądać podobnie do kodu z listingu 1-2:

Plik: Cargo.toml

[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

Listing 1-2: Zawartość pliku Cargo.toml wygenerowanego przez cargo new

Plik jest w formacie TOML (Tom’s Obvious, Minimal Language) (Oczywisty, Minimalistyczny Język Toma - przyp. tłum.), którego Cargo używa do konfiguracji.

Pierwsza linia, [package], jest nagłówkiem sekcji, której kolejne wyrażenia konfigurują pakiet. W miarę dodawania informacji do tego pliku, dodamy też inne sekcje.

Następne trzy linie ustalają informacje konfiguracyjne, których Cargo potrzebuje do kompilacji twojego programu: nazwę, wersję, i dane o używanej edycji Rusta. O kluczu edition będzie mowa w Dodatku E.

Ostatnia linia, [dependencies], rozpoczyna sekcję, gdzie wyszczególnia się wszystkie zależności twojego projektu. W Ruście pakiety z kodem źródłowym nazywane są skrzyniami (crates). Do tego projektu nie będziemy potrzebować żadnych skrzyń, ale do programu w rozdziale drugim owszem. Wówczas przyda nam się sekcja zależności.

Otwórz teraz plik src/main.rs i przyjrzyj się zawartości:

Plik: src/main.rs

fn main() {
    println!("Hello, world!");
}

Cargo wygenerował dla ciebie program „Witaj, świecie!”, prawie taki sam jak ten, jak napisaliśmy w listingu 1-1 (tyle, że w języku angielskim)! Różnice między naszym poprzednim projektem, a tym wygenerowanym przez Cargo są takie, że w Cargo kod źródłowy trafia do podkatalogu src, a w katalogu głównym pozostaje plik konfiguracyjny Cargo.toml.

Cargo zakłada, że kod źródłowy znajduje się w podkatalogu src, dzięki czemu katalog główny wykorzystany jest tylko na pliki README, informacje o licencjach, pliki konfiguracyjne i wszystko inne, co nie jest kodem. Używanie Cargo pomaga utrzymać ci własne projekty w należytym porządku. Na wszystko jest miejsce i wszystko jest na swoim miejscu.

Jeżeli zacząłeś(-aś) jakiś projekt bez użycia Cargo, taki jak nasz poprzedni z katalogu hello_world, możesz przekonwertować go na wersję kompatybilną z Cargo, przenosząc kod źródłowy do podkatalogu src i tworząc odpowiedni plik Cargo.toml.

Budowanie i uruchamianie projektu z Cargo

Przyjrzyjmy się teraz, jakie są różnice w budowaniu i uruchamianiu programu „Witaj, świecie!” poprzez Cargo. Aby zbudować swój projekt, z poziomu głównego katalogu hello_cargo wprowadź polecenie:

$ cargo build
   Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs

Spowoduje to utworzenie pliku wykonywalnego w target/debug/hello_cargo (lub target\debug\hello_cargo.exe pod Windowsem), zamiast w katalogu bieżącym. Ponieważ domyślnie budowana jest wersja debug programu, Cargo umieszcza skompilowany plik binarny w katalogu debug. Plik można uruchomić następującym poleceniem:

$ ./target/debug/hello_cargo # lub .\target\debug\hello_cargo.exe pod Windowsem
Hello, world!

Jeśli wszystko przebiegło prawidłowo, Hello, world! powinno wyświetlić się w oknie terminala. Uruchomienie cargo build za pierwszym razem powoduje dodatkowo utworzenie przez Cargo nowego pliku w katalogu głównym o nazwie Cargo.lock, który wykorzystywany jest do śledzenia dokładnych wersji zależności w twoim projekcie. Ponieważ bieżący projekt nie posiada zależności, zawartość pliku jest dość licha. Nie będziesz musiał własnoręcznie modyfikować tego pliku; Cargo zajmie się tym za ciebie.

Właśnie zbudowaliśmy projekt poleceniem cargo build i uruchomiliśmy go przez ./target/debug/hello_cargo. Możemy również użyć cargo run, żeby skompilować i uruchomić program za jednym rzutem:

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/hello_cargo`
Hello, world!

Większość programistów używa cargo run, bo jest ono wygodniejsze i łatwiejsze do zapamiętania od użycia cargo build i pełnej ścieżki do zbudowanego pliku binarnego.

Zauważ, że tym razem nie wyświetliła się informacja o tym, że Cargo kompilował hello_cargo. Program wywnioskował, że zawartość plików nie uległa zmianie, więc po prostu uruchomił binarkę. Gdyby kod źródłowy został zmodyfikowany, Cargo przebudowałby projekt przed jego uruchomieniem i wówczas informacja na ekranie wyglądałaby następująco:

$ 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!

Mamy jeszcze do dyspozycji cargo check. To polecenie szybko sprawdzi twój kod, celem upewnienia się, że skompilowałby się on prawidłowo, ale nie tworzy pliku wykonywalnego:

$ cargo check
   Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs

Jaki jest cel pomijania tworzenia binarki? Taki, że cargo check jest często o wiele szybsze od cargo build, ponieważ cały krok generowania pliku wykonywalnego jest pomijany. Jeśli masz zwyczaj sprawdzać swoją pracę w trakcie pisania kodu, użycie cargo check przyspieszy proces! Wielu Rustowców okresowo uruchamia cargo check, żeby sprawdzić, czy wszystko się kompiluje, a cargo build dopiero, kiedy zdecydują się na uruchomienie binarki.

Podsumujmy, co do tej pory nauczyliśmy się o Cargo:

  • Możemy stworzyć projekt używając cargo new.
  • Możemy zbudować projekt poleceniami cargo build.
  • Możemy zbudować i uruchomić projekt w jednym kroku z użyciem cargo run.
  • Możemy zbudować projekt bez tworzenia binarki, aby sprawdzić błędy używając cargo check.
  • Zamiast umieszczać pliki wynikowe budowania w tym samym katalogu co nasz kod, Cargo umieści je w podkatalogu target/debug.

Dodatkową zaletą używania Cargo jest to, że polecenia są identyczne, bez względu na system operacyjny, pod którym pracujesz. Od tego momentu nie będziemy zatem podawać osobnych instrukcji dla Linuksa i macOS czy Windowsa.

Budowanie do publikacji

Gdy twój projekt jest już gotowy do publikacji, możesz użyć polecenia cargo build --release celem przeprowadzenia kompilacji z optymalizacjami. Spowoduje to utworzenie pliku wykonywalnego w podkatalogu target/release zamiast w target/debug. Przeprowadzone optymalizacje sprawiają, że twój program w Ruście wykonuje się szybciej, ale jednocześnie jego kompilacja trwa dłużej. Dlatego też istnieją dwa różne profile: jeden rozwojowy, kiedy zależy ci na szybkim i częstym budowaniu oraz drugi, przeznaczony do zbudowania ostatecznej wersji, która trafi do użytkownika. Nie będzie ona wielokrotnie przebudowywana, ale wykonywać się będzie tak szybko, jak to tylko możliwe. Jeżeli prowadzisz testy czasu wykonywania swojego kodu, pamiętaj o wywołaniu cargo build --release i testowaniu pliku wykonywalnego z podkatalogu target/release.

Cargo jako konwencja

W przypadku prostych projektów, Cargo nie wnosi wielu korzyści w porównaniu z używaniem prostego rustc, ale udowodni swoją wartość w miarę postępów. Przy skomplikowanych projektach złożonych z wielu plików lub mających wiele zależności, zezwolenie Cargo na koordynację budowania znacznie ułatwia pracę.

Nawet jeśli projekt hello_cargo jest prosty, używa już sporej części arsenału narzędzi, z którymi będziesz mieć do czynienia przez pozostały okres swojej kariery z Rustem. Rzeczywiście, rozpoczęcie pracy nad jakimkolwiek istniejącym projektem sprowadza się do wydania kilku poleceń: check out kodu w Git, wejście do katalogu roboczego i budowanie:

$ git clone przyklad.org/jakisprojekt
$ cd jakisprojekt
$ cargo build

Więcej informacji o Cargo można znaleźć w jego dokumentacji.

Podsumowanie

Jesteś już na dobrej drodze do rozpoczęcia podróży z Rustem! W tym rozdziale nauczyłeś(-aś) się, jak:

  • Zainstalować najnowszą, stabilną wersję Rusta z użyciem rustup,
  • Uaktualnić Rusta do nowszej wersji,
  • Otwierać lokalną kopię dokumentacji,
  • Napisać program „Witaj, świecie!” używając bezpośrednio rustc,
  • Stworzyć i uruchomić nowy projekt używając konwencji Cargo.

To świetna pora na stworzenie poważniejszego programu, aby przyzwyczaić się do czytania i pisania kodu w Ruście. W następnym rozdziale zbudujemy program grający w zgadywankę. Jeśli jednak chcesz zacząć naukę o działaniu powszechnych pojęć programistycznych w Ruście, przejdź do rozdziału 3, a następnie wróć do rozdziału 2.

Piszemy grę zgadywankę

Rozpocznijmy zabawę z Rustem tworząc razem praktyczny projekt. Ten rozdział zapozna cię z kilkoma podstawowymi konceptami Rusta, prezentując ich użycie w prawdziwym programie. Dowiesz się, co oznaczają let, match, metoda, funkcja powiązana (associated function), nauczysz się, jak używać skrzyń (crates), i wielu innych rzeczy! Dokładniejsze omówienie tych tematów znajduje się w dalszych rozdziałach. W tym rozdziale przećwiczysz jedynie podstawy.

Zaimplementujemy klasyczny problem programistyczny dla początkujących: grę zgadywankę. Oto zasady: program generuje losową liczbę całkowitą z przedziału od 1 do 100. Następnie prosi użytkownika o wprowadzenie liczby z tego przedziału. Gdy użytkownik wprowadzi swoją odpowiedź, program informuje, czy podana liczba jest niższa czy wyższa od wylosowanej. Gdy gracz odgadnie wylosowaną liczbę, program wyświetla gratulacje dla zwycięzcy i kończy działanie.

Tworzenie nowego projektu

Aby stworzyć nowy projekt, wejdź do folderu projects utworzonego w rozdziale 1 i za pomocą Cargo wygeneruj szkielet projektu, w ten sposób:

$ cargo new guessing_game
$ cd guessing_game

Pierwsza komenda, cargo new, jako argument przyjmuje nazwę projektu (guessing_game). W kolejnej linii komenda cd przenosi nas do nowo utworzonego folderu projektu.

Spójrz na wygenerowany plik Cargo.toml:

Plik: 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]

Jak już widziałeś w rozdziale 1, cargo new tworzy dla ciebie program „Hello World!”. Otwórz plik src/main.rs:

Plik: src/main.rs

fn main() {
    println!("Hello, world!");
}

Teraz skompilujemy i uruchomimy ten program w jednym kroku za pomocą komendy 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!

Komenda run jest przydatna, kiedy chcesz w szybki sposób testować kolejne iteracje rozwoju projektu. Tak właśnie jest w przypadku naszej gry: chcemy testować każdy krok, zanim przejdziemy do kolejnego.

Otwórz jeszcze raz plik src/main.rs. W tym pliku będziesz pisał kod programu.

Przetwarzanie odpowiedzi

Pierwsza część programu będzie prosiła użytkownika o podanie liczby, przetwarzała jego odpowiedź i sprawdzała, czy wpisane przez niego znaki mają oczekiwaną postać. Zaczynamy od wczytania odpowiedzi gracza. Przepisz kod z listingu 2-1 do pliku src/main.rs.

Plik: src/main.rs

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Listing 2-1: Implementacja wczytująca odpowiedź użytkownika i wypisująca ją na ekran

Powyższy fragment kodu zawiera dużo informacji - przeanalizujmy go kawałek po kawałku. Aby wczytać odpowiedź gracza a następnie wyświetlić ją na ekranie, musimy dołączyć do programu bibliotekę io (input/output). Biblioteka io pochodzi z biblioteki standardowej (znanej jako std):

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Domyślnie Rust posiada zestaw elementów zdefiniowanych w bibliotece standardowej, które importuje do każdego programu. Ten zestaw nazywany jest prelude i można zobaczyć co zawiera w dokumentacji biblioteki standardowej.

Jeśli typu, którego chcesz użyć, nie ma w prelude, musisz go jawnie zaciągnąć używając słowa use. Skorzystanie z biblioteki std::io dostarcza wielu pożytecznych mechanizmów związanych z io, włącznie z funkcjonalnością do wczytywania danych wprowadzonych przez użytkownika.

Tak jak mówiliśmy już w rozdziale 1, każdy program rozpoczyna wykonanie w funkcji main.

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

fn deklaruje nową funkcję, () informuje, że funkcja ta nie przyjmuje żadnych parametrów, a { otwiera ciało funkcji.

W rozdziale 1 nauczyłeś się również, że println! jest makrem, które wyświetla zawartość stringa na ekranie:

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Powyższy fragment kodu wypisuje na ekranie informację, na czym polega gra, i prosi użytkownika o wprowadzenie odgadniętej przez niego liczby.

Zapisywanie wartości w zmiennych

Teraz stworzymy zmienną do zapisywania odpowiedzi użytkownika, w ten sposób:

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Program robi się coraz bardziej interesujący! W tej krótkiej linii wiele się dzieje. Instrukcji let używamy do utworzenia zmiennej. Tutaj kolejny przykład:

let apples = 5;

W tej linii tworzona jest nowa zmienna o nazwie apples, do której przypisana jest wartość 5. W Ruście wszystkie zmienne są domyślnie niemutowalne (stałe), co oznacza, że nadana im na początku wartość nie zmieni się. We’ll be discussing this concept in detail in the „Variables and Mutability” section in Chapter 3. Poniższy przykład pokazuje, jak stawiając słowo kluczowe mut przed nazwą zmiennej stworzyć zmienną mutowalną:

let apples = 5; // immutable
let mut bananas = 5; // mutable

Uwaga: Znaki // rozpoczynają komentarz, który ciągnie się do końca linii. Rust ignoruje zawartość komentarzy. Komentarze omówimy bardziej szczegółowo w rozdziale 3.

Powróćmy do naszej gry-zgadywanki. Teraz już wiesz, że let mut guess utworzy mutowalną zmienną o nazwie guess. Po prawej stronie znaku przypisania (=) jest wartość, która jest przypisywana do guess, i która jest wynikiem wywołania funkcji String::new, tworzącej nową instancję Stringa. String to dostarczany przez bibliotekę standardową typ tekstowy, gdzie tekst ma postać UTF-8 i może się swobodnie rozrastać.

Znaki :: w wyrażeniu ::new wskazują na to, że new jest funkcją powiązaną (associated function) z typem String. Funkcje powiązane są zaimplementowane na danym typie, w tym przypadku na Stringu, a nie na konkretnej instancji typu String (niektóre języki programowania nazywają to metodą statyczną). Funkcja new tworzy nowy, pusty String. W przyszłości spotkasz się z funkcjami new dla wielu różnych typów, ponieważ jest to standardowa nazwa dla funkcji tworzącej nową instancję danego typu.

Podsumowując, linia let mut guess = String::new(); stworzyła mutowalną zmienną, która jest obecnie przypisania do nowej, pustej instancji typu String. Uff!

Pobieranie danych od użytkownika

Przypominasz sobie, że załączyliśmy do programu obsługę wejścia/wyjścia z biblioteki standardowej przy pomocy linii use std::io;? Teraz wywołamy z stdin funkcję znajdującą się w module io, które pozwoli nam na pobranie danych od użytkownika:

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Gdybyśmy nie zaimportowali io za pomocą use std::io na początku programu, aby wywołać tę funkcję musielibyśmy napisać std::io::stdin. Funkcja stdin zwraca instancję std::io::Stdin, która jest typem reprezentującym uchwyt do standardowego wejścia dla twojego terminala.

Dalszy fragment kodu, .read_line(&mut guess), wywołuje metodę read_line na uchwycie wejścia standardowego, aby w ten sposób wczytać znaki wprowadzone przez gracza. Do metody read_line podajemy argument &mut guess, by wskazać gdzie zapisać wczytane znaki.

Zadaniem metody read_line jest wziąć to, co użytkownik wpisze na wejście standardowe i dodać to do podanego string (bez nadpisania jego zawartości), który przyjmuje ona jako argument. String ten musi być mutowalny, aby metoda była w stanie go zmodyfikować.

Znak & wskazuje na to, że argument guess jest referencją. Referencja oznacza, że wiele kawałków kodu może operować na jednej instancji danych, bez konieczności kopiowania tej danej kilkakrotnie. Referencje są skomplikowane, a jedną z głównych zalet Rusta jest to, jak bezpiecznie i łatwo można ich używać. Do dokończenia tego programu nie musisz znać wielu szczegółów na ten temat: rozdział 4 omówi referencje bardziej wnikliwie. Póki co wszystko co musisz wiedzieć o referencjach to to, że podobnie jak zmienne, domyślnie są niemutowalne. Dlatego musimy napisać &mut guess, a nie &guess, aby dało się tę referencję modyfikować.

Obsługa potencjalnych błędów z użyciem Result

Nie skończyliśmy jeszcze analizy tej linii kodu. Pomimo tego że doszliśmy już do trzeciej linii tekstu, wciąż jest to część pojedynczej, logicznej linii kodu. Kolejną częścią jest ta metoda:

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Moglibyśmy napisać ten kod tak:

io::stdin().read_line(&mut guess).expect("Błąd wczytania linii");

Jednakże taka długa linia jest trudna do czytania, więc lepiej ją podzielić. Często warto złamać linię i wprowadzić dodatkowe wcięcie, by poprawić czytelność długich wywołań ze składnią typu .nazwa_metody(). Teraz omówimy, co ta linia robi.

Jak już wspomnieliśmy wcześniej, read_line zapisuje tekst wpisany przez użytkownika do stringa przekazanego jako argument. Ale również zwraca wartość typu Result. Result jest enumeracją, często nazywaną enumem lub typamem wyliczeniowym. Typ wyliczeniowy to typ, który może mieć stały zestaw wartości, nazywanych wariantami (variants).

Chapter 6 will cover enums in more detail. The purpose of these Result types is to encode error-handling information.

Możliwe wartości Result to Ok i Err. Ok oznacza, że operacja powiodła się sukcesem i wewnątrz obiektu Ok znajduje się poprawnie wygenerowana wartość. Err oznacza, że operacja nie powiodła się, i obiekt Err zawiera informację o przyczynach niepowodzenia.

Obiekty typu Result, tak jak obiekty innych typów, mają zdefiniowane dla siebie metody. Instancja Result ma metodę expect, którą możesz wywołać. Jeśli dana instancja Result będzie miała wartość Err, wywołanie metody expect spowoduje zakończenie się programu i wyświetlenie na ekranie wiadomości, którą podałeś jako argument do expect. Sytuacje, gdy metoda read_line zwraca Err, najprawdopodobniej są wynikiem błędu pochodzącego z systemu operacyjnego. Gdy zaś zwrócony Result ma wartość Ok, expect odczyta wartość właściwą, przechowywaną przez Ok, i zwróci tę wartość, gotową do użycia w programie. W tym przypadku wartość ta odpowiada liczbie bajtów, które użytkownik wprowadził na wejście.

Gdybyśmy pominęli wywołanie expect, program skompilowałby się z ostrzeżeniem:

$ 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 ostrzega, że nie zrobiliśmy nic z wartością Result zwróconą z read_line, a co za tym idzie, program nie obsłużył potencjalnego błędu. Sposobem na pozbycie się tego ostrzeżenia jest dopisanie obsługi błędów. Tutaj jednak chcemy, by program zakończył się, gdy nie uda się odczytać odpowiedzi użytkownika, więc możemy użyć expect. O wychodzeniu ze stanu błędu przeczytasz w rozdziale 9.

Wypisywanie wartości z pomocą println! i placeholderów

Poza klamrą zamykającą program, w kodzie który dotychczas napisaliśmy została już tylko jedna linia do omówienia:

use std::io;

fn main() {
    println!("Zgadnij numer!");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Ta linia wyświetla na ekranie łańcuch, w którym zapisaliśmy odpowiedź użytkownika. Zestaw {} nawiasów nawiasów klamrowych to placeholder: pomyśl o {} jak o małych szczypcach kraba, które trzymają wartość w miejscu. Podczas wypisywania wartości zmiennej, nazwa zmiennej może znajdować się wewnątrz nawiasów klamrowych. By wypisać wynik wyrażenia, umieść puste nawiasy klamrowe w łańcuchu formatującym, a za łańcuchem same wyrażenia, oddzielone przecinkami, po jednym dla kolejnych pustych nawiasów klamrowych. Wyświetlanie zmiennej i wyniku wyrażenia w jednym wywołaniu println! wyglądałoby tak:

#![allow(unused)]
fn main() {
let x = 5;
let y = 10;

println!("x = {x} i y + 2 = {}", y + 2);
}

Ten kod wypisze na ekran x = 5 i y + 2 = 12.

Testowanie pierwszej część programu

Przetestujmy pierwszą część Zgadywanki. Uruchom grę poleceniem cargo run:

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
     Running `target/debug/guessing_game`
Zgadnij numer!
Podaj swoją liczbę:
6
Wybrana przez ciebie liczba: 6

W tym miejscu pierwsza część gry jest gotowa: wczytujemy odpowiedź użytkownika z klawiatury i wypisujemy ją na ekranie.

Generowanie sekretnej liczby

Następnie musimy wygenerować sekretną liczbę, którą gracz będzie próbował odgadnąć. Sekretna liczba powinna zmieniać się przy każdym uruchomieniu programu, aby gra bawiła więcej niż raz. Użyjmy losowej liczby z przedziału od 1 do 100, żeby odgadnięcie jej nie było zbyt trudne. W bibliotece standardowej Rusta nie ma jeszcze obsługi liczb losowych, dlatego musimy sięgnąć do skrzyni rand.

Więcej funkcjonalności z użyciem skrzyń

Zapamiętaj: skrzynia (ang. crate) to kolejkcja plików źródłowych Rusta. Projekt, który budujemy, to skrzynia binarna (binary crate), czyli plik wykonywalny. Skrzynia rand to library crate, czyli biblioteka stworzona do używania w innych programach.

Z użyciem Cargo dodawanie zewnętrznych pakietów jest bajecznie proste. Aby móc używać rand w naszym kodzie, wystarczy zmodyfikować plik Cargo.toml tak, aby zaciągał skrzynię rand jako zależność do projektu. Otwórz Cargo.toml i dodaj na końcu, pod nagłówkiem sekcji [dependencies], poniższą linię. Upewnij się, że podałeś rand dokładnie tak jak poniżej, z z tym samym numerem wersji. Inaczej kody zawarte w tym tutorialu mogą nie zadziałać:

Plik: Cargo.toml

[dependencies]
rand = "0.8.5"

Plik Cargo.toml podzielony jest na sekcje, których ciało zaczyna się po nagłówku i kończy się w miejscu, gdzie zaczyna się kolejna sekcja. W sekcji [dependencies] informujesz Cargo, jakich zewnętrznych skrzyń i w której wersji wymaga twój projekt. Tutaj przy skrzyni rand znajduje się specyfikator wersji 0.8.5. Cargo rozumie Semantic Versioning (nazywane tez czasem SemVer), które to jest standardem zapisywania numeru wersji. Numer 0.8.5 jest właściwie skrótem do ^0.8.5, które oznacza wersję conajmniej 0.8.5, ale poniżej 0.9.0.

Cargo considers these versions to have public APIs compatible with version 0.8.5, and this specification ensures you’ll get the latest patch release that will still compile with the code in this chapter. Any version 0.9.0 or greater is not guaranteed to have the same API as what the following examples use.

Teraz bez zmieniania niczego w kodzie przekompilujmy projekt, tak jak przedstawia 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

Listing 2-2: Wynik po wywołaniu cargo build po dodaniu zależności do skrzyni rand

Być może u siebie zobaczysz inne numery wersji (jednak wszystkie będą kompatybilne z kodem, dzięki SemVer!), inne linie (zależnie od systemu operacyjnego), lub linie wydrukowane w innej kolejności.

Teraz kiedy mamy już zdefiniowaną jakąś zewnętrzną zależność, Cargo ściąga najnowsze wersje wszystkich skrzyń z rejestru, który jest kopią danych z Crates.io. Crates.io to miejsce, gdzie ludzie związani z Rustem publikują dla innych swoje otwarto-źródłowe projekty.

Po zaktualizowaniu rejestru Cargo sprawdza sekcję [dependencies] i ściąga skrzynie, jeśli jakichś brakuje. W tym przypadku, pomimo że podaliśmy do zależności jedynie skrzynę rand, Cargo ściągnął jeszcze inne skrzynie, od których zależny jest rand. Po ich ściągnięciu Rust je kompiluje, a następnie, mając już dostępne niezbędne zależności, kompiluje projekt.

Gdybyś teraz bez wprowadzania jakichkolwiek zmian wywołał ponownie cargo build, nie zobaczyłbyś nic ponad linię Finished. Cargo wie, że zależności są już ściągnięte i skompilowane, i że nie zmieniałeś nic w ich kwestii w pliku Cargo.toml. Cargo również wie, że nie zmieniałeś nic w swoim kodzie, więc jego też nie rekompiluje. Nie ma nic do zrobienia, więc po prostu kończy swoje działanie.

Jeśli wprowadzisz jakąś trywialną zmianę w pliku src/main.rs, zapiszesz, a następnie ponownie zbudujesz projekt, zobaczysz jedynie dwie linijki na wyjściu:

$ cargo build
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs

Te dwie linie pokazują, że Cargo przebudował uwzględniając jedynie twoją maleńką zmianą z pliku src/main.rs. Zależności nie zmieniły się, więc Cargo wie, że może użyć ponownie te, które już raz ściągnął i skompilował.

Plik Cargo.lock zapewnia powtarzalność kompilacji

Cargo posiada mechanizm, który zapewnia że za każdym razem, gdy ty lub ktokolwiek inny będziecie przebudowywać projekt, kompilowane będą te same artefakty: Cargo użyje zależności w konkretnych wersjach, chyba że wskażesz inaczej. Na przykład, co by się stało, gdyby za tydzień wyszła nowa wersja skrzyni rand 0.8.6, która zawierałaby poprawkę istotnego błedu, ale jednocześnie wprowadza regresję, która zepsuje twój kod? Odpowiedzią na ten problem jest plik Cargo.lock, który został stworzony w momencie, gdy po raz pierwszy wywołałeś cargo build. Znajduje się on teraz w twoim folderze guessing_game.

Kiedy po raz pierwszy budujesz dany projekt, Cargo sprawdza wersje każdej z zależności, tak by kryteria były spełnione, i wynik zapisuje w pliku Cargo.lock. Od tego czasu przy każdym kolejnym budowaniu, Cargo widząc, że plik Cargo.lock istnieje, będzie odczytywać z niego wersje zależności do pobrania, zamiast na nowo próbować je określać. Dzięki temu twoje kompilacje są automatycznie reprodukowalne. Innymi słowy, twój projekt będzie wciąż używał wersji 0.8.5, do czasu aż sam jawnie nie wykonasz aktualizacji. Ponieważ plik Cargo.lock jest ważny dla powtarzalnych kompilacji, jest on często umieszczany w systemie kontroli wersji wraz z resztą kodu w projekcie.

Aktualizowanie skrzyni do nowszej wersji

Kiedy chcesz zmienić wersję skrzyni na nowszą, możesz skorzystać z komendy update dostarczanej przez Cargo, która zignoruje plik Cargo.lock i wydedukuje na nowo najświeższe wersje skrzyń, które pasują do twojej specyfikacji z Cargo.toml. Cargo zapisze te wersje do pliku Cargo.lock. Jednak domyślnie Cargo będzie szukało jedynie wersji większej od 0.8.5 i mniejszej od 0.9.0. Jeśli skrzynia rand została wypuszczona w dwóch nowych wersjach, 0.8.6 i 0.9.0, po uruchomieniu cargo update zobaczysz taki wynik:

$ cargo update
    Updating crates.io index
    Updating rand v0.8.5 -> v0.8.6

Cargo ignoruje wydanie 0.9.0. Teraz zauważysz również zmianę w pliku Cargo.lock - wersja skrzyni rand będzie ustawiona na 0.8.6. Gdybyś chciał używać rand w wersji 0.9.0 lub jakiejkolwiek z serii 0.9.x, musiałbyś zaktualizować plik Cargo.toml do takiej postaci:

[dependencies]
rand = "0.9.0"

Następnym razem gdy wywołasz cargo build, Cargo zaktualizuje rejestr dostępnych skrzyń i zastosuje nowe wymagania co do wersji skrzyni rand, zgodnie z tym co zamieściłeś w pliku.

Można by jeszcze wiele mówić o Cargo i jego ekosystemie. Wrócimy do tego w rozdziale 14. Na razie wiesz wszystko, co w tej chwili potrzebujesz. Dzięki Cargo ponowne używanie bibliotek jest bardzo łatwe, więc Rustowcy mogą pisać mniejsze projekty, składające się z wielu skrzyń.

Generowanie Losowej Liczby

A teraz użyjmy w końcu skrzyni rand by wygerować liczbę do zgadnięcia. Zmodyfikujmy plik src/main.rs, tak jak pokazano na listingu 2-3:

Plik: src/main.rs

use std::io;
use rand::Rng;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("Sekretna liczba to: {secret_number}");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Listing 2-3: Zmiany potrzebne do wygenerowania losowej liczby

Najpierw dodajmy linię use rand::Rng;. Rng to cecha (ang. trait), która definiuje metody implementowane przez generator liczb losowych. Cecha ta musi być widoczna w zasięgu, w którym chcemy tych metod używać. Cechy szczegółowo omówimy w rozdziale 10.

Dodajemy również dwie linie w środku. W pierwszej linii wywołujemy funkcję rand::thread_rng, która daje nam gotowy do użycia konkretny generator liczb losowych: taki, który jest lokalny dla wątku wywołującego i seedowany z systemu operacyjnego. Następnie wywołujemy metodę gen_range tego generatora. Ta metoda zdefiniowana jest w cesze Rng, którą włączyliśmy wyrażeniem use rand::Rng;. Zakres typu start..=koniec jest inkluzywny, zawiera obie podane wartości granicznej, dolną i górną. Dlatego podaliśmy 1..=100, aby zażądać liczby pomiędzy 1 a 100.

Uwaga: Wiedza, której cechy użyć i które funkcje i metody ze skrzyni wywoływać, nie jest czymś co po prostu wiesz. Instrukcja jak używać danej skrzyni znajduje się zawsze w jej dokumentacji. Kolejną przydatną komendą Cargo jest polecenie cargo doc --open, które lokalnie zbuduje dokumentację dostarczaną przez wszystkie zależności, jakich używasz, i otworzy ją w przeglądarce. Gdyby, przykładowo, interesowały cię inne funkcjonalności ze skrzyni rand, wpisz cargo doc --open i wybierz rand z paska po lewej.

Druga dodana przez nas linia wypisuje na ekranie sekretną liczbę. Jest to przydatne podczas implementowania do testowania programu i zostanie usunięte w finalnej wersji. Gra nie byłaby zbyt ekscytująca, gdyby program podawał sekretną liczbę od razu na starcie!

Spróbuj uruchomić program kilka razy:

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 2.53 secs
     Running `target/debug/guessing_game`
Zgadnij liczbę!
Sekretna liczba to: 7
Podaj swoją liczbę:
4
Wybrana przez ciebie liczba: 4
$ cargo run
     Running `target/debug/guessing_game`
Zgadnij liczbę!
Sekretna liczba to: 83
Podaj swoją liczbę:
5
Wybrana przez ciebie liczba: 5

Za każdym razem powinieneś/powinnaś otrzymać inny sekretny numer, jednak zawsze z zakresu od 1 do 100. Dobra robota!

Porównywanie Odpowiedzi z Sekretnym Numerem

Teraz, kiedy już mamy odpowiedź gracza i wylosowaną sekretną liczbę, możemy je porównać. Ten krok przedstawiony jest na listingu 2-4. Ten kod nie będzie się jeszcze kompilował. Zaraz wyjaśnimy dlaczego.

Plik: src/main.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    // --snip--
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("Sekretna liczba to: {secret_number}");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Za mała!"),
        Ordering::Greater => println!("Za duża!"),
        Ordering::Equal => println!("Jesteś zwycięzcą!"),
    }
}

Listing 2-4: Obsługa możliwych rezultatów operacji porównywania dwóch liczb

Po pierwsze dodaliśmy kolejne use, które wprowadza nam do zasięgu typ std::cmp::Ordering z biblioteki standardowej. Ordering jest enumem, takim jak Result, ale ma inne warianty: Less, Greater, i Equal. Są to trzy możliwe wyniki porównywania dwóch wartości.

Następnie dopisaliśmy na końcu pięć nowych linii wykorzystujących typ Ordering. Metoda cmp porównuje dwie wartości. Można wywołać ją na dowolnym obiekcie, który da się porównywać. Przyjmuje ona referencję do drugiego obiektu, z którym chcemy porównać pierwszy: tutaj porównujemy guess do secret_number. cmp zwraca wariant enuma Ordering (którego typ zaciągnęliśmy poprzez wyrażenie use). Za pomocą wyrażenia match, na podstawie wartości Ordering zwróconej przez wywołanie cmp z wartościami guess z secret_number, decydujemy, co zrobić dalej.

Wyrażenie match składa się z odnóg. Każda odnoga składa się ze wzorca dopasowania i kodu, który ma się wykonać, jeśli wartość podana na początku wyrażenia match będzie pasowała do danego wzorca. Rust bierze wartość podaną do match i przegląda kolejno wzorce ze wszystkich odnóg. Wzorce i konstrukcja match to potężne mechanizmy w Ruście, które pozwolą wyrazić w kodzie wiele różnych scenariuszy i pomogą zapewnić obsługę ich wszystkich. Zostaną one omówione szczegółowo, odpowiednio w rozdziale 6 i 18.

Przeanalizujmy na przykładzie, co dokładnie dzieje się z użytym tutaj wyrażeniem match. Powiedzmy, że użytkownik wybrał liczbę 50, a losowo wygenerowana sekretna liczba to 38.

Kiedy kod porówna 50 do 38, metoda cmp zwróci wartość Ordering::Greater, ponieważ 50 jest większe niż 38. Zatem match otrzymuje tutaj wartość Ordering::Greater. Match sprawdza wzorzec w pierwszej odnodze, Ordering::Less, ale wartość Ordering::Greater nie pasuje do wzorca Ordering::Less, więc kod z tej odnogi jest pomijany i sprawdzana jest następna odnoga. Wzorzec z następnej odnogi, Ordering::Greater, pasuje do Ordering::Greater! Powiązany kod w tej odnodze jest wykonywany i na ekranie pojawia się napis Za duża!. Wyrażenie match kończy wykonanie po pierwszym znalezionym dopasowaniu, więc ostatnia odnoga nie będzie już w tym przypadku sprawdzana.

Niemniej, kod z listingu 2-4 jeszcze się nie skompiluje. Spróbujmy:

$ 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

Komunikat błędu wskazuje, że typy są niezgodne. Rust jest silnie statycznym typowanym językiem. Jednak również wspiera dedukcję typów. Kiedy napisaliśmy let guess = String::new(), Rust potrafił wywnioskować, że guess powinno być Stringiem, dzięki czemu nie musieliśmy pisać typu jawnie. Z drugiej strony, secret_number jest typem numerycznym. Wiele typów numerycznych może przyjmować wartość spomiędzy 1 a 100: i32, 32-bitowa liczba całkowita; u32, 32-bitowa liczba całkowita bez znaku; i64, 64-bitowa liczba całkowita; a także inne. Jeśli nie wskazano inaczej, to domyślnie Rust wybiera i32, co jest typem secret_number, jeśli nie wpisaliśmy gdzieś indziej w kodzie jakiejś informacji, która spowoduje że Rust wybierze inny typ. Przyczyną błędu jest to, że Rust nie potrafi porównywać stringa z typem numerycznym.

Ostatecznie musimy przekonwertować stringa, którego program wczytał jako wejście z klawiatury, do postaci typu numerycznego, który można porównać matematycznie do sekretnej liczby. Osiągamy to dodając kolejną linię do ciała funkcji main:

Plik: src/main.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("Sekretna liczba to: {secret_number}");

    println!("Podaj swoją liczbę:");

    // --snip--

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    let guess: u32 = guess.trim().parse().expect("Podaj liczbę!");

    println!("Wybrana przez ciebie liczba: {guess}");

    match guess.cmp(&secret_number) {
        Ordering::Less => println!("Za mała!"),
        Ordering::Greater => println!("Za duża!"),
        Ordering::Equal => println!("Jesteś zwycięzcą!"),
    }
}

Dodana linia to:

let guess: u32 = guess.trim().parse().expect("Podaj liczbę!");

Tworzymy tu zmienną o nazwie guess. Ale czekaj, czy program przypadkiem nie ma już zmiennej o takiej nazwie? Owszem ma, ale szczęśliwie Rust pozwala przesłaniać poprzednią wartość zmiennej guess nową wartością. Przesłanianie (shadowing) pozwala użyć ponownie nazwy guess, zamiast zmuszać nas do tworzenia dwóch osobnych zmiennych, takich jak przykładowo guess_str i guess. Rozdział 3 opowiada więcej o przesłanianiu zmiennych. Teraz wspomnimy jedynie, że funkcjonalność ta jest często używana w sytuacjach, gdy konieczna jest konwersja wartości z jednego typu do drugiego.

Nowej zmiennej guess nadajemy wartość wyrażenia guess.trim().parse(). Zmienna guess w tym wyrażeniu odnosi się do pierwotnej zmiennej guess, która była stringiem zawierającym dane wczytane z klawiatury. Metoda trim z interfejsu Stringa spowoduje usunięcie wszelkich białych znaków znajdujących się na początku lub końcu stringa. Jest to niezbędne, bo aby sparsować String do typu u32, String ten powinien zawierać jedynie znaki numeryczne. Jednakże, aby zadowolić funkcję read_line, użytkownik musi wcisnąć enter. Po wciśnięciu enter znak nowej linii jest dopisywany do stringa. Przykładowo, jeśli użytkownik wpisał 5 i wcisnął enter, to guess przyjmie postać: 5\n. Znak \n reprezentuje nową linię, czyli wynik wciśnięcia enter. (Pod Windowsem w wyniku wciśnięcia enter otrzymujemy \r\n.) Metoda trim usunie niechciane \n, dzięki czemu w stringu pozostanie jedynie 5.

Metoda parse parsuje stringa do innego typu. Tu używamy jej by otrzymać typ liczbowy. Co więcej, musimy powiedzieć Rustowi, jakiego dokładnie typu oczekujemy, używając wyrażenia let guess: u32. Dwukropek (:) po guess informuje Rusta, że dalej podany będzie typ zmiennej. Rust ma kilka wbudowanych typów numerycznych; u32, którą tu podaliśmy, to 32-bitowa liczba całkowita bez znaku. Jest to dobry domyślny wybór dla małych liczb dodatnich. O innych typach numerycznych przeczytasz w rozdziale 3.

Dodatkowo, dzięki anotacji u32 w tym przykładowym programie i porównaniu tej liczby z secret_number, Rust wywnioskuje, że secret_number też powinien być typu u32. Zatem porównanie zachodzi pomiędzy dwiema wartościami tego samego typu!

Wywołanie parse często może zakończyć się niepowodzeniem. Jeśli, na przykład, string będzie zawierał A👍%, to jego konwersja do liczby nie może się udać. Z tego względu metoda parse zwraca typ Result, podobnie jak metoda read_line (wspominaliśmy o tym wcześniej w sekcji „Obsługa potencjalnych błędów z użyciem Result). Potraktujemy ten Result w ten sam sposób, używając ponownie metody expect. Jeśli parse zwróci wariant Err (ponieważ nie udało się stworzyć liczby ze stringa), wywołanie expect spowoduje zawieszenie się gry i wypisanie na ekran podanego przez nas tekstu. Gdy zaś parse powiedzie się i poprawnie skonwertuje stringa do liczby, zwrócony Result będzie wariantem Ok, a expect zwróci liczbę zaszytą w wartości Ok.

Teraz uruchomimy program!

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 0.43 secs
     Running `target/debug/guessing_game`
Zgadnij liczbę!
Sekretna liczba to: 58
Podaj swoją liczbę:
  76
Wybrana przez ciebie liczba: 76
Za duża!

Nieźle! Pomimo tego że dodaliśmy spacje przed liczbą, program wciąż poprawnie rozpoznał, że użytkownik wybrał liczbę 76. Uruchom program kilka razy, aby sprawdzić jak program reaguje na różne wejścia: podaj właściwą liczbę, za wysoką, następnie za niską.

Nasza gra już z grubsza działa, ale użytkownik może odgadywać liczbę tylko jeden raz. Zmieńmy to dodając pętlę!

Wielokrotne zgadywanie dzięki pętli

Słowo kluczowe loop (pętla) tworzy pętlę nieskończoną. Dodamy taką pętlę, żeby dać graczowi więcej szans na odgadnięcie liczby:

Plik: src/main.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    // --snip--

    println!("Sekretna liczba to: {secret_number}");

    loop {
        println!("Podaj swoją liczbę:");

        // --snip--


        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Błąd wczytania linii");

        let guess: u32 = guess.trim().parse().expect("Podaj liczbę!");

        println!("Wybrana przez ciebie liczba: {guess}");

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Za mała!"),
            Ordering::Greater => println!("Za duża!"),
            Ordering::Equal => println!("Jesteś zwycięzcą!"),
        }
    }
}

Jak widzisz, przenieśliśmy do pętli cały kod następujący po zachęcie gracza do odgadnięcia liczby. Pamiętaj, żeby zwiększyć wcięcia linii wewnątrz pętli o kolejne cztery spacje, następnie uruchom program ponownie. Niestety teraz program pyta o wprowadzenie odgadniętej liczby w nieskończoność i użytkownik nie może z niego łatwo wyjść!

Użytkownik może zawsze zatrzymać program używając skrótu klawiszowego ctrl-c. Lecz jest jeszcze inny sposób, żeby uciec temu nienasyconemu potworowi, jak wspomnieliśmy w dyskusji o parse w „Porównywanie odpowiedzi gracza z sekretnym numerem”: wprowadzenie znaku, który nie jest liczbą, spowoduje zawieszenie się programu. Można z tego skorzystać, aby wyjść z programu, tak jak pokazujemy poniżej:

$ cargo run
   Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
    Finished dev [unoptimized + debuginfo] target(s) in 1.50 secs
     Running `target/debug/guessing_game`
Zgadnij liczbę!
Sekretna liczba to: 59
Podaj swoją liczbę:
45
Wybrana przez ciebie liczba: 45
Za mała!
Podaj swoją liczbę:
60
Wybrana przez ciebie liczba: 60
Za duża!
Podaj swoją liczbę:
59
Wybrana przez ciebie liczba: 59
Jesteś zwycięzcą!
Podaj swoją liczbę:
quit
thread 'main' panicked at 'Podaj liczbę!: ParseIntError { kind: InvalidDigit }', src/main.rs:28:47
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Wpisanie quit faktycznie powoduje wyjście z programu, ale taki sam skutek daje wprowadzenie dowolnego innego ciągu znaków nienumerycznych. Zamykanie programu w ten sposób nie jest zbyt optymalne. Dodatkowo, chcielibyśmy, aby gra zatrzymała się, kiedy gracz wprowadzi poprawny numer.

Wychodzenie z programu po poprawnym odgadnięciu

Dodanie wyrażenia break sprawi, że gra zakończy się, kiedy gracz wygra.

Plik: src/main.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("Sekretna liczba to: {secret_number}");

    loop {
        println!("Podaj swoją liczbę:");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Błąd wczytania linii");

        let guess: u32 = guess.trim().parse().expect("Podaj liczbę!");

        println!("Wybrana przez ciebie liczba: {guess}");

        // --snip--

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Za mała!"),
            Ordering::Greater => println!("Za duża!"),
            Ordering::Equal => {
                println!("Jesteś zwycięzcą!");
                break;
            }
        }
    }
}

Dodanie linii break po Jesteś zwycięzcą! powoduje, że program opuszcza pętlę, gdy gracz odgadnie poprawnie sekretny numer. Wyjście z pętli jest równoważne z zakończeniem pracy programu, ponieważ pętla jest ostatnią częścią funkcji main.

Obsługa niepoprawnych danych wejściowych

W celu dalszego ulepszenia gry zróbmy tak, żeby program, zamiast zawieszać się, ignorował wprowadzone dane nienumeryczne, a użytkownik mógł zgadywać dalej. Możemy to osiągnąć edytując linię, w której guess jest konwertowane ze Stringa do u32, w sposób przedstawiony na listingu 2-5.

Plik: src/main.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("Sekretna liczba to: {secret_number}");

    loop {
        println!("Podaj swoją liczbę:");

        let mut guess = String::new();

        // --snip--

        io::stdin()
            .read_line(&mut guess)
            .expect("Błąd wczytania linii");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("Wybrana przez ciebie liczba: {guess}");

        // --snip--

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Za mała!"),
            Ordering::Greater => println!("Za duża!"),
            Ordering::Equal => {
                println!("Jesteś zwycięzcą!");
                break;
            }
        }
    }
}

Listing 2-5: Ignorowanie wejścia nieliczbowego i pytanie o kolejne liczby, zamiast zawieszania programu

Zamieniliśmy expect na wyrażenie match by zamienić zakończenie się programu na obsługuję błędów. Pamiętaj, że typem zwracanym przez parse jest Result, a Result jest typem wyliczeniowym, który ma warianty Ok oraz Err. Używamy tutaj wyrażenia match, podobnie jak robiliśmy to z wynikiem Ordering zwracanym przez metodę cmp.

Jeśli parse jest w stanie pomyślnie zamienić stringa w liczbę, zwróci wariant Ok, zawierający w sobie liczbę otrzymaną w konwersji. Wartość Ok odpowiada wzorcowi z pierwszej gałęzi match, zatem match zwróci wartość num, która została obliczona i zapisana wewnątrz wartości Ok. Ta liczba zostanie przypisana do nowoutworzonej przez nas zmiennej guess.

Jeśli jednak parse nie jest w stanie przekonwertować stringa na liczbę, zwróci wartość Err, która zawiera dodatkowe informacje o błędzie. Wartość Err nie pasuje do wzorca Ok(num) z pierwszej odnogi match, ale pasuje do wzorca Err(_) z drugiej odnogi. Znak podkreślenia, _, pasuje do wszystkich wartości; w tym przypadku mówimy, że do wzorca mają pasować wszystkie wartości Err, bez znaczenia na to jakie dodatkowe informacje mają one w środku. Program zatem wykona instrukcje z drugiego ramienia, continue, co oznacza że program ma przejść do kolejnej iteracji pętli i poprosić o nową liczbę. Dzięki temu program ignoruje wszystkie problemy jakie może napotkać parse!

Teraz wszystko w naszym programie powinno działać zgodnie z oczekiwaniami. Wypróbujmy to:

$ 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`
Zgadnij liczbę!
Sekretna liczba to: 61
Podaj swoją liczbę:
10
Wybrana przez ciebie liczba: 10
Za mała!
Podaj swoją liczbę:
99
Wybrana przez ciebie liczba: 99
Za duża!
Podaj swoją liczbę:
foo
Podaj swoją liczbę:
61
Wybrana przez ciebie liczba: 61
Jesteś zwycięzcą!

Wspaniale! Jeszcze jedna drobna poprawka i nasza gra w zgadywankę będzie już skończona. Program wciąż wyświetla sekretny numer. To było przydatne podczas testów, ale na dłuższą metę psułoby zabawę. Usuńmy println! odpowiedzialną za wyświetlanie sekretnego numeru. Listing 2-6 pokazuje końcową wersję programu.

Plik: src/main.rs

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    loop {
        println!("Podaj swoją liczbę:");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Błąd wczytania linii");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("Wybrana przez ciebie liczba: {guess}");

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Za mała!"),
            Ordering::Greater => println!("Za duża!"),
            Ordering::Equal => {
                println!("Jesteś zwycięzcą!");
                break;
            }
        }
    }
}

Listing 2-6: Kompletna gra w zgadywankę

Podsumowanie

Właśnie udało ci się zbudować grę w zgadywankę. Gratulacje!

Ten projekt w praktyczny sposób zapoznał cię z wieloma konceptami Rusta: let, match, funkcjami, używaniem zewnętrznych skrzyń, i innymi. W najbliższych rozdziałach koncepty te będą omówione bardziej szczegółowo. Rozdział 3 omawia koncepty obecne w większości języków programowania, takie jak zmienne, typy danych czy funkcje, i prezentuje jak należy w nich korzystać w Ruście. Rozdział 4 odkrywa system własności, mechanizm który wyróżna Rusta spośród innych języków. Rozdział 5 omawia składnię struktur i metod, a rozdział 6 wyjaśnia, jak działają typy numeryczne.

This project was a hands-on way to introduce you to many new Rust concepts: let, match, functions, the use of external crates, and more. In the next few chapters, you’ll learn about these concepts in more detail. Chapter 3 covers concepts that most programming languages have, such as variables, data types, and functions, and shows how to use them in Rust. Chapter 4 explores ownership, a feature that makes Rust different from other languages. Chapter 5 discusses structs and method syntax, and Chapter 6 explains how enums work.

Powszechne koncepcje programistyczne

W tym rozdziale zostaną omówione pojęcia i rozwiązania, które pojawiają się niemal w każdym języku programowania oraz ich zastosowanie w Ruście. Wiele języków programowania ma dużo wspólnych cech. Żadna z koncepcji zaprezentowanych w tym rozdziale nie jest unikalna dla Rusta, ale omówimy je w kontekście Rusta i wytłumaczymy zasady ich używania.

W szczególności dowiesz się czym są oraz jak wykorzystywać: zmienne, podstawowe typy danych, funkcje, komentarze i przepływ sterowania. Te fundamentalne elementy pojawią się w każdym programie napisanym w Rust, a poznanie ich wcześnie zapewni ci silne podstawy do dalszej nauki.

Słowa kluczowe

Rust, podobnie jak w inne języki programowania, posiada grupę słów kluczowych, które są zarezerwowane wyłącznie do użytku w kontekście językowym. Zapamiętaj, że nie możesz wykorzystywać tych słów jako nazw zmiennych, ani funkcji. Większość słów kluczowych ma specjalne znaczenie i będziesz ich używał do wykonywania różnych operacji w swoich programach; niektóre nie mają obecnie jeszcze żadnego zastosowania, lecz zostały zarezerwowane dla funkcjonalności, które mogą zostać dodane w przyszłości do Rusta. Listę słów kluczowych znajdziesz w Dodatku A.

Zmienne i ich modyfikowalność

Tak jak wspomniano w rozdziale „Storing Values with Variables” , zmienne są domyślnie niemodyfikowalne (niemutowalne, ang. immutable). To jeden z wielu prztyczków, którymi Rust zachęca cię do tworzenia kodu w pełni wykorzystującego mechanizmy bezpieczeństwa i prostoty współbieżności, które oferuje ten język programowania. Jednakże nadal możesz uczynić zmienne modyfikowalnymi. Przyjrzyjmy się bliżej temu, jak i dlaczego Rust zachęca cię do preferowania niemodyfikowalności zmiennych oraz czemu czasem możesz chcieć zrezygnować z tej własciwości.

Gdy zmienna jest niemodyfikowalna, po przypisaniu wartości do danej nazwy, nie można później zmienić tej wartości. Aby to zobrazować, utworzymy nowy projekt o nazwie variables w folderze projects korzystając z komendy cargo new --bin variables.

Następnie w nowo utworzonym folderze variables, odnajdź i otwórz src/main.rs, zmień kod w tym pliku na poniższy, który jednak jeszcze nie skompiluje się poprawnie:

Plik: src/main.rs

fn main() {
    let x = 5;
    println!("Wartość x wynosi: {x}");
    x = 6;
    println!("Wartość x wynosi: {x}");
}

Zapiszmy zmiany i uruchommy program, używając cargo run. Powinniśmy otrzymać następujący komunikat o błędzie związanym z niemutowalnością:

$ 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: make this binding mutable: `mut x`
3 |     println!("Wartość x wynosi: {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

Ten przykład pokazuje, jak kompilator pomaga ci odnajdywać błędy w twoich programach. Mimo że błędy kompilacji mogą być denerwujące, świadczą jedynie o tym, że twój program jeszcze nie działa prawidłowo. Nie wykonuje w bezpieczny sposób tego, co chcesz, by robił. Tw błędy nie oznaczają jednak, że nie jesteś dobrym programistą! Nawet doświadczeni Rustowcy nadal napotykają błędy podczas kompilacji.

Otrzymany komunikat błedu `` cannot assign twice to immutable variable x``` oznacza, że nie można dwukrotnie przypisać wartości do niemodyfikowalnej zmiennej x`. Pierwotnie nadanej wartości nie można zmienić.

To ważne, że napotykamy błędy w trakcie kompilacji, gdy próbujemy zmienić wartość, którą wcześniej określiliśmy jako niemodyfikowalną, gdyż takie działanie może prowadzić do podatności i błędów w programie. Jeżeli pierwsza część kodu opiera się na założeniu, że dana wartość nigdy nie ulegnie zmianie, a inna część kodu zmienia tę wartość, pierwsza część kodu może przestać wykonywać swoje zadanie poprawnie. Przyczyna tego rodzaju błędów może być trudna do zidentyfikowania po wystąpieniu, szczególnie gdy druga część kodu zmienia daną wartość tylko czasami.

W Ruście, kompilator gwarantuje, że jeżeli ustawimy wartość na niemodyfikowalną, to naprawdę nigdy nie ulegnie zmianie. Oznacza to, że czytając i pisząc kod, nie musisz ciągle sprawdzać gdzie i jak wartość może się zmienić. W związku z tym tworzony przez ciebie kod staje się łatwiejszy do zrozumienia.

Jednak modyfikowalność może być też bardzo użyteczna. Zmienne są tylko domyślnie niemodyfikowalne. Można uczynić je modyfikowalnymi, dodając mut przed nazwą zmiennej. Poza tym, że dzięki dodaniu mut możliwa jest modyfikacja wartości zmiennej, jest ono też wyraźnym sygnałem dla osób, które będą czytały kod w przyszłości. Informuje, że inne części kodu będą modyfikować wartość danej zmiennej.

Na przykład, zmieńmy kod w src/main.rs na poniższy:

Plik: src/main.rs

fn main() {
    let mut x = 5;
    println!("Wartość x wynosi: {x}");
    x = 6;
    println!("Wartość x wynosi: {x}");
}

Gdy teraz uruchomimy program, otrzymamy:

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/variables`
Wartość x wynosi: 5
Wartość x wynosi: 6

Możemy zmienić wartość, do której odwołuje się x z 5 na 6, dzięki wykorzystaniu mut. W niektórych przypadkach będziesz chciał uczynić zmienną modyfikowalną, ponieważ sprawi to, że pisanie kodu stanie się wygodniejsze niż gdyby tworzono go tylko z użyciem niemodyfikowalnych zmiennych.

Stałe

Brak możliwości modyfikacji wartości zmiennej może przypominać ci inne rozwiązanie programistyczne, które wykorzystuje wiele języków programowania: stałe (constants). Podobnie jak zmienne niemodyfikowalne, stałe to wartości, których nie można zmienić, przypisane do nazw, ale występuje też kilka różnic między stałymi i zmiennymi.

Po pierwsze, nie możesz używać mut do stałych. Stałe są nie tylko domyślnie niemodyfikowalne. One są zawsze niemodyfikowalne. Do deklaracji stałej wykorzystujemy słowo kluczowe const zamiast let i zawsze musimy określić typ wartości. Typy danych i ich adnotacje omówimy już niedługo, w następnym podrozdziale "Typy Danych", więc nie przejmuj się na razie szczegółami. Po prostu zapamiętaj, że zawsze musisz nadać stałej typ danych.

Stałe mogą być deklarowane w każdym zasięgu, włączając w to zasięg globalny, dzięki czemu są bardzo użyteczne w przypadku wartości, z których korzysta wiele części kodu.

Ostatnia różnica to, że stałym można nadać wartości tylko za pomocą stałych wyrażeń, a nie takich obliczanych dopiero trakcie działania programu.

Oto przykład deklaracji stałej:

#![allow(unused)]
fn main() {
const TRZY_GODZINY_W_SEKUNDACH: u32 = 60 * 60 * 3;
}

Nazwą stałej jest TRZY_GODZINY_W_SEKUNDACH, zaś jej wartością jest iloczyn: 60 (liczba sekund w minucie), kolejnej 60 (liczba minut w godzienie) i 3 (liczba godzin którą chcemy odliczyć w programie). Konwencja nazewnicza Rusta dla stałych zobowiązuje do wykorzystywanie tylko dużych liter z podkreśleniami między słowami. The compiler is able to evaluate a limited set of operations at compile time, which lets us choose to write out this value in a way that’s easier to understand and verify, rather than setting this constant to the value 10,800. See the Rust Reference’s section on constant evaluation for more information on what operations can be used when declaring constants.

Stałe są dostępne przez cały okres działania programu w zasięgu, w którym zostały zadeklarowane, stają się tym samym dobrym wyborem dla wartości w twojej domenie aplikacji, które mogą być wykorzystywane przez różne elementy programu, takich jak maksymalna liczba punktów, które może uzyskać gracz, czy też prędkość światła.

Nazywanie predefiniowanych wartości używanych przez twój program stałymi jest użyteczne w przekazywaniu znaczenia wykorzystywanych wartości dla przyszłych współtwórców kodu. Pomaga to w utrzymaniu predefiniowanych wartości w jednym miejscu i ułatwia ich późniejsze uaktualnianie.

Przesłanianie

Jak widzieliśmy w poradniku do gry zgadywanki w rozdziale 2, można zadeklarować nową zmienną o takiej samej nazwie, jak miała dawna zmienna, i ta nowa zmienna przesłania dawną zmienną. Rustowcy mówią, że pierwsza zmienna jest przesłoniona przez drugą. I właśnie tą nową zmienną użyje kompilator w miejscach wystąpienia jej nazwy, aż do czasu gdy i ona nie zostanie przesłonięta, albo nie skończy się zasięg jej życia. Możemy przesłonić zmienną poprzez wykorzystanie tej samej nazwy zmiennej i ponowne użycie słowa kluczowego let, tak jak poniżej:

Plik: src/main.rs

fn main() {
    let x = 5;

    let x = x + 1;

    {
        let x = x * 2;
        println!("Wartość x w wewnętrznym bloku kodu wynosi: {x}");
    }

    println!("Wartość x wynosi: {x}");
}

Ten program najpierw deklaruje zmienną x o wartość 5. Następnie tworzy nową zmienną x powtarzając let x =, pobiera oryginalną wartość zmiennej i dodaje do niej 1 w wyniku czego wartość x to obecnie 6. Użycie deklaracji let po raz trzeci również przesłania x i tworzy kolejną zmienną, której wartość jest ustalona poprzez przemnożenie poprzedniej wartość przez 2, czyli na 12. Gdy uruchomimy ten program, otrzymamy:

$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/variables`
Wartość x w wewnętrznym bloku kodu wynosi: 12
Wartość x wynosi: 6

To nie to samo, co nadanie mut zmiennej, gdyż jeżeli przypadkowo spróbujemy ponownie przypisać wartość do zmiennej, nie wykorzystując słowa kluczowego let otrzymamy błąd kompilacji. Dzięki użyciu let, możemy przeprowadzić kilka transformacji na wartości, pozostawiając przy tym zmienną niemodyfikowalną.

Inna różnica między mut i przesłanianiem to, że za każdym razem, gdy używamy słowa kluczowego let, tworzymy nową zmienną, co oznacza, że możemy wybrać inny typ danych, ale ponownie użyć tej samej nazwy zmiennej. Na przykład, powiedzmy, że nasz program prosi użytkownika o pokazanie ilości spacji, jaka ma zostać umieszczona między jakimś tekstem, poprzez wpisanie tych spacji, ale my tak naprawdę chcemy przechowywać tę wartość jako liczbę:

fn main() {
    let spaces = "   ";
    let spaces = spaces.len();
}

Powyższa konstrukcja jest dozwolona, gdyż pierwsza zmienna spaces typu string, to zupełnie inna zmienna niż druga zmienna spaces typu numerycznego. Dzięki przesłanianiu nie musimy wykorzystywać dwóch różnych nazw np. spaces_str i spaces_num. Zamiast tego, ponownie korzystamy z prostszej nazwy spaces. Jednak, jeżeli spróbowalibyśmy użyć mut dla tej zmiennej otrzymalibyśmy błąd kompilacji:

fn main() {
    let mut spaces = "   ";
    spaces = spaces.len();
}

Błąd mówi o tym, że nie możemy zmodyfikować typu zmiennej:

$ 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

Teraz gdy poznaliśmy już działanie zmiennych, przyjrzyjmy się bliżej typom danych, jakich mogą być zmienne.

Typy danych

Każda wartość w Ruście ma pewien typ danych, dzięki czemu Rust wie, z jakim rodzajem danych ma do czynienia i jak z nimi pracować. Przyjrzymy się bliżej dwóm grupom typów danych: skalarnym i złożonym.

Pamiętaj, że Rust jest językiem statycznie typowanym (statically typed), co oznacza, że podczas kompilacji musi znać typy danych wszystkich zmiennych obecnych w kodzie. Zazwyczaj kompilator może wywnioskować typ danych, którego chcemy użyć na podstawie użytej wartość i sposobu jej wykorzystywania. W przypadku gdy wiele typów danych spełnia dane założenia, przykładowo gdy w rozdziale 2 w sekcji "Porównywanie odpowiedzi gracza z sekretnym numerem" konwertowaliśmy String do typu numerycznego wykorzystując funkcję parse musimy dodać adnotację typu danych:

#![allow(unused)]
fn main() {
let guess: u32 = "42".parse().expect("To nie liczba!");
}

Jeżeli w powyższym kodzie nie dodalibyśmy adnotacji typu danych : u32, Rust wyświetliłby następujący komunikat o błędzie, mówiący o tym, że kompilator potrzebuje więcej informacji, aby określić, jakiego typu danych chcemy użyć:

$ cargo build
   Compiling brak_adnotacji_typow v0.1.0 (file:///projects/brak_adnotacji_typow)
error[E0282]: type annotations needed
 --> src/main.rs:2:9
  |
2 |     let guess = "42".parse().expect("To nie liczba!");
  |         ^^^^^
  |
help: consider giving `guess` an explicit type
  |
2 |     let guess: _ = "42".parse().expect("To nie liczba!");
  |              +++

For more information about this error, try `rustc --explain E0282`.
error: could not compile `brak_adnotacji_typow` due to previous error

Można napotkać różne zapisy poszczególnych typów danych.

Typy skalarne

Typ skalarny reprezentuje pojedynczą wartość. Rust posiada 4 główne, skalarne typy danych: całkowity (ang. integer), zmiennoprzecinkowy (ang. floating-point numbers), logiczny (ang. Boolean) i znakowy (ang. characters). Możesz kojarzyć je z innych języków programowania. Zobaczmy jak działają w Ruście.

Typy całkowite

Liczba całkowita to liczba nieposiadająca części ułamkowej. Jeden z typów całkowitych, u32, wykorzystywaliśmy w rozdziale 2. Ten typ danych określa, że wartość, do której się odnosi, jest liczbą całkowitą bez znaku (typy całkowite ze znakiem zaczynają się od i zamiast u), która zajmuje 32 bity pamięci. Tabela 3-1 pokazuje typy całkowite wbudowane w Rusta. Każdy z wariantów w kolumnach Ze znakiem i Bez znaku (na przykład i16) może zostać użyty do zadeklarowania typu danych liczby całkowitej.

Tabela 3-1: Typy całkowite w Ruście

RozmiarZe znakiemBez znaku
8-bitówi8u8
16-bitówi16u16
32-bityi32u32
64-bityi64u64
128-bitówi128u128
archisizeusize

Każdy z wariantów może posiadać znak lub nie, a także ma określony rozmiar. Nazwy Ze znakiem i Bez znaku odnoszą się do tego, czy dana liczba może być ujemna, czy tylko dodatnia -- inaczej mówiąc, czy liczba musi posiadać znak (ze znakiem), czy też nie, gdyż wiadomo, że zawsze będzie dodatnia (bez znaku). Można to porównać do zapisywania liczb na kartce, gdy znak ma znaczenie, zapisujemy go -- odpowiednio plus lub minus przed liczbą, ale gdy liczba jest dodatnia i w danym kontekście nie jest to konieczne, pomijamy znak. Liczby całkowite ze znakiem przechowywane są z pomocą Kodu uzupełnień do dwóch (jeżeli nie jesteś pewien, co to oznacza, możesz poszukać informacji w internecie; wyjaśnienie jest poza zakresem materiału zawartego w tej książce).

Każdy wariant ze znakiem może przechowywać liczby od -(2n - 1) do 2n - 1 - 1 włącznie, gdzie n to liczba bitów, które wykorzystuje dany wariant. Tak więc i8 może przechowywać liczby od -(27) do 27 - 1, co daje zakres od -128 do 127. Warianty bez znaku mogą przechowywać liczby od 0 do 2n - 1, więc u8 może przechowywać liczby od 0 do 28 - 1, co daje zakres od 0 do 255.

Dodatkowo rozmiar typów isize oraz usize zależy od architektury komputera, na którym uruchamiasz swój program: 64 bity na komputerze o 64-bitowej architekturze i 32 bity na komputerze o 32-bitowej architekturze.

Możesz zapisywać literały liczb całkowitych w każdej z form uwzględnionych w Tabeli 3-2. Zauważ, że wszystkie literały mogące oznaczać różne typy numeryczne, pozwalają na użycie przyrostka by wskazać typ, np. 57u8. Literały numeryczne dopuszczają też wizualny separator _ poprawiający czytelności, np. 1_000 oznacza tą samą wartość co 1000.

Tabela 3-2: Literały liczb całkowitych w Ruście

Literały liczbowePrzykład
Dziesiętny98_222
Szesnastkowy0xff
Ósemkowy0o77
Binarny0b1111_0000
Bajt (tylko u8)b'A'

W takim razie skąd masz wiedzieć, którego typu całkowitego użyć? Jeżeli nie masz pewności, to zazwyczaj dobrze jest zacząć od typów domyślnych wykorzystywanych przez Rusta. Dla liczb całkowitych to i32. Z typów isize i usize korzystamy głównie przy indeksowaniu różnego rodzaju kolekcji danych.

Przekroczenie zakresu liczb całkowitych

Załóżmy, że mamy zmienną typy u8, która może przechowywać wartości między 0 i 255. Jeżeli spróbujemy przypisać tej zmiennej wartość nie mieszczącą się w podanym zakresie, np. 256, nastąpi przekroczenie zakresu liczb całkowitych. Rust posiada kilka ciekawych zasad dotyczących takiej sytuacji. Kiedy program kompilowany jest w trybie debugowania, Rust dołącza do niego mechanizmy powodujące jego "spanikowanie" (panic) w momencie wystąpienia przekroczenia zakresu liczb całkowitych. Rust wykorzystuje termin "panikowania" programu wtedy, gdy program kończy działaniem zwracając błąd; panikowanie szczegółowiej omówimy w sekcji „Nieodwracalne błędy z panic! w rozdziale 9.

Kiedy kompilujemy program w trybie produkcyjnym z włączoną flagą --release, Rust nie dołącza do programu mechanizmów wykrywających przekroczenia zakresu liczb całkowitych, które spowodują spanikowanie programu. Zamiast tego w przypadku wystąpienia przekroczenia zakresu, Rust wykona operację nazywaną zawinięciem uzupełnia do dwóch. Krótko mówiąc, wartości większe niż maksymalna dla danego typu danych zostaną "zawinięte w koło" do mniejszych wartości, odpowiednich dla danego typu danych. Na przykład w przypadku u8, 256 zostanie zamienione na 0, 257 na 1 itd. Program nie spanikuje, ale zmiennym zostaną przypisane inne wartości niż byś tego oczekiwał. Poleganie na zawinięciu uzupełnia do dwóch jest uważane za błąd.

Przepełnienia można obsłużyć jawnie. W tym celu można skorzystać z następujących rodzin metod, zapewnionych prymitywnym typom liczbowym przez bibliotekę standardową:

  • zawijanie we wszystkich trybach kompilacji za pomocą metod wrapping_*, takich jak wrapping_add;
  • zwracanie wartość None jeśli wystąpiło przepełnienie za pomocą metod checked_*;
  • zwracanie wartość liczbowej wraz z wartością logiczną (boolean) wskazującą, czy wystąpiło przepełnienie za pomocą metod overflowing_*;
  • nasycenie do minimalnych lub maksymalnych wartości za pomocą metod saturating_*.

Typy zmiennoprzecinkowe

Rust posiada też dwa prymitywne typy danych dla liczb zmiennoprzecinkowych, czyli liczb posiadających część ułamkową. Typy zmiennoprzecinkowe w Ruście to: f32 i f64, o rozmiarach, odpowiednio, 32 i 64 bity. Domyślnie Rust wykorzystuje f64, gdyż nowoczesne procesory wykonują operacje na tym typie niemal tak szybko, jak na f32, a jest on bardziej precyzyjny.

Oto przykład pokazujący liczby zmiennoprzecinkowe w akcji:

Plik: src/main.rs

fn main() {
    let x = 2.0; // f64

    let y: f32 = 3.0; // f32
}

Liczby zmiennoprzecinkowe są reprezentowane zgodnie ze standardem IEEE-754. Typ f32 to liczba zmiennoprzecinkowa zapisana w wyżej wymienionym standardzie z pojedynczą precyzją, a f64 -- z podwójną.

Operacje arytmetyczne

Rust wspiera podstawowe operacje arytmetyczne na wszystkich numerycznych typach danych: dodawanie, odejmowanie, mnożenie, dzielenia i resztę z dzielenia. Dzielenie na typach liczb całkowitych odrzuca resztę z dzielenia, zaokrąglając w kierunku zera. Poniższy kod przedstawia przykładowe użycie każdej z wymienionych operacji w połączeniu z instrukcją let:

Plik: src/main.rs

fn main() {
    // dodawanie
    let sum = 5 + 10;

    // odejmowanie
    let difference = 95.5 - 4.3;

    // mnożenie
    let product = 4 * 30;

    // dzielenie
    let quotient = 56.7 / 32.2;
    let truncated = -5 / 3; // Results in -1

    // reszta
    let remainder = 43 % 5;
}

Każde z wyrażeń w tych instrukcjach korzysta z operatora matematycznego i jest wyliczane do pojedynczej wartości, która następnie jest przypisywana do zmiennej. Listę wszystkich operatorów obsługiwanych przez Rusta znajdziesz w Dodatku B.

Typ logiczny (Boolean)

W Ruście, podobnie jak w wielu innych językach programowania, typ Boolean może przyjąć jedną z dwóch wartości: true lub false. Boolean ma wielkość jednego bajta. Typ logiczny w Ruście jest deklarowany z pomocą bool. Na przykład:

Plik: src/main.rs

fn main() {
    let t = true;

    let f: bool = false; // z jawną deklaracją typu
}

Jednym z głównych zastosowań typu Boolean są wyrażenia logiczne, takie jak if. Działanie wyrażenia if w Ruście omówimy w sekcji Kontrola przepływu.

Typ znakowy

Do tej pory pracowaliśmy tylko z liczbami, ale Rust wspiera też litery. Najprostszym typ znakowym jest char. Oto przykłady jego deklaracji:

Plik: src/main.rs

fn main() {
    let c = 'z';
    let z: char = 'ℤ'; // with explicit type annotation
    let heart_eyed_cat = '😻';
}

Proszę zauważyć, że literały typu char są zapisywane z użyciem pojedynczego cudzysłowia, w przeciwieństwie do literałów łańcuchowych, które korzystają z podwójnego cudzysłowia. Typ char w Ruście ma wielkość czterech bajtów i reprezentuje Skalarną Wartość Unikod, co oznacza, że można w nim przedstawić dużo więcej niż tylko znaki ASCII. Litery akcentowane; chińskie, japońskie i koreańskie symbole; emoji; pola o zerowej długości to wszystko poprawne wartości dla typu char w Ruście. Skalarne Wartości Unikod mieszczą się w zakresach od U+0000 do U+D7FF i od U+E000 do U+10FFFF włącznie. Jednak „znak” nie jest naprawdę ideą w Unikodzie, więc twój intuicyjny sposób postrzegania tego, czym jest „znak” może nie być zgodny z tym, czym w rzeczywistości jest char w Ruście. Szczegółowo omówimy ten temat w "Ciągach znaków" w rozdziale 8.

Typy złożone

Typy złożone mogą grupować wiele wartości w jeden typ danych. Rust posiada dwa prymitywne typy złożone: krotki i tablice.

Krotki

Krotka pozwala na zgrupowanie pewnej liczby wartości o różnych typach danych w jeden złożony typ danych. Krotka ma stałą długość. Po zadeklarowaniu nie może się powiększyć ani pomniejszyć.

Aby stworzyć krotkę, zapisujemy w nawiasie okrągłym listę wartości oddzielonych przecinkami. Każda pozycja w krotce ma pewien typ danych, przy czym wszystkie wartości nie muszą mieć tego samego typu danych. W tym przykładzie dodaliśmy opcjonalne adnotacje typów danych:

Plik: src/main.rs

fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
}

Zmienna tup odnosi się do całej krotki, gdyż krotka jest traktowana jak jeden złożony element. Aby uzyskać dostęp do wartości, które składają się na krotkę, możemy skorzystać z dopasowywania do wzorca i rozdzielić wartość krotki, tak jak poniżej:

Plik: src/main.rs

fn main() {
    let tup = (500, 6.4, 1);

    let (x, y, z) = tup;

    println!("Wartość y wynosi: {y}");
}

Powyższy program najpierw tworzy krotkę i przypisuje ją do zmiennej tup. Następnie korzysta ze wzorca w połączeniu z instrukcją let, aby przetransformować tup w trzy niezależne zmienne x, y, i z. Tę operację nazywamy destrukturyzacją, gdyż rozdziela pojedynczą krotkę na trzy części. Na końcu, program wypisuje wartość zmiennej y, czyli 6.4.

Możemy też uzyskać bezpośredni dostęp do elementu krotki, wykorzystując znak kropki (.) oraz indeks wartości, do której chcemy uzyskać dostęp. Na przykład:

Plik: 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;
}

Powyższy program tworzy krotkę x, a następnie uzyskuje dostęp do jej elementów wykorzystując ich indeksy. Podobnie, jak w większości języków programowania pierwszy indeks w krotce ma wartość 0.

The tuple without any values has a special name, unit. This value and its corresponding type are both written () and represent an empty value or an empty return type. Expressions implicitly return the unit value if they don’t return any other value.

Tablice

Innym sposobem na stworzenie kolekcji wartości jest użycie tablicy. W przeciwieństwie do krotki każdy element tablicy musi być tego samego typu. Tablice w Ruście różnią się od tablic znanych z paru innych języków programowania tym, że mają stały rozmiar. Raz zadeklarowane nie mogą zwiększyć ani zmniejszyć swojego rozmiaru.

W Ruście, aby umieścić wartości w tablicy, zapisujemy je jako lista rozdzieloną przecinkami, wewnątrz nawiasów kwadratowych:

Plik: src/main.rs

fn main() {
    let a = [1, 2, 3, 4, 5];
}

Tablice są przydatne, gdy chcesz umieścić dane na stosie, a nie na stercie (Stos i stertę omówimy w rozdziale 4) lub gdy chcesz mieć pewność, że ilość elementów nigdy się nie zmieni. Jednak tablica nie jest tak elastyczna, jak typ wektorowy. Wektor jest podobnym typem kolekcji, dostarczanym przez bibliotekę standardową, ale może zwiększać i zmniejszać swój rozmiar. Jeżeli nie jesteś pewien, czy użyć wektora, czy tablicy, prawdopodobnie powinieneś użyć wektora. [Rozdział 8] szczegółowo opisuje wektory i ich działanie.

Jednak tablice są bardziej przydatne, gdy wiadomo, że liczba elementów nie zmieni się. Przykładowo gdy w programie chcemy używać nazw miesięcy, lepiej przechowywać je w tablicy niż w wektorze, ponieważ wiemy, że potrzebujemy dokładnie 12 elementów:

#![allow(unused)]
fn main() {
let months = ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec",
              "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"];
}

Typ tablicy zapisujemy używając nawiasów kwadratowych, wewnątrz których umieszczamy typ każdego z elementów, po nim średnik, a następnie liczbę elementów w tablicy, tak jak poniżej:

#![allow(unused)]
fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
}

Powyżej i32 to typ każdego elementu. Po średniku liczba 5 oznacza, że w tej tablicy znajdzie się pięć elementów.

By stworzyć tablicę mającą te same wartości dla każdego elementu, można podać tę wartość, po niej średnik i liczbę elementów, całość obejmując nawiasami kwadratowymi:

#![allow(unused)]
fn main() {
let a = [3; 5];
}

Tablica a będzie zawierać 5 elementów, a każdy z nich początkowo przyjmie wartość 3. Taki sam rezultat osiągnąłby taki zapis: let a = [3, 3, 3, 3, 3];, ale ten pierwszy jest krótszy.

Uzyskiwanie Dostępu do Elementów Tablicy

Tablica to obszar pamięci ulokowany na stosie. Możesz uzyskać dostęp do elementów tablicy, korzystając z indeksowania, tak jak poniżej:

Plik: src/main.rs

fn main() {
    let a = [1, 2, 3, 4, 5];

    let first = a[0];
    let second = a[1];
}

W tym przykładzie, zmienna o nazwie first otrzyma wartość 1, ponieważ taka wartość znajduje się w tablicy na miejscu o indeksie [0]. Zmienna o nazwie second otrzyma wartość 2 od pozycji w tablicy o indeksie [1].

Próba Uzyskania Dostępu do Niepoprawnego Elementu Tablicy

Co się stanie, gdy spróbujemy uzyskać dostęp do elementu, który jest poza tablicą? Zmienimy wcześniejszy przykład na poniższy kod, który pobiera indeks tablicy od użytkownika, używając kodu podobnego do tego z gry zgadywanki z rozdziału 2:

Plik: 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!("Wartość elementu pod indeksem {index} wynosi: {element}");
}

Nie wystąpiły żadne błędy w trakcie kompilacji. Po uruchomieniu za pomocą cargo run i podaniu 0, 1, 2, 3, lub 4, program wypisuje wartość z tablicy o podanym indeksie. Jeśli jednak w zamian zostanie podana liczba niebędąca poprawnym indeksem tej tablicy, jak np. 10, pojawi się następujący komunikat:

thread 'main' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:19:19
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Uruchomienie programu poskutkowało błędem wykonania w momencie użycia niepoprawnej wartości dla operacji indeksowania. Program zakończył działanie w tym momencie z komunikatem o błędzie i nie wykonał końcowego println!. Przy próbie dostępu do elementu z wykorzystaniem indeksowania, Rust sprawdza, czy podany indeks jest mniejszy niż długość tablicy. Jeżeli ten indeks jest większy lub równy długości tablicy, program spanikuje. To sprawdzenie musi się odbyć w czasie wykonywania, szczególnie w tym przypadku, w którym kompilator nie może wiedzieć, jaką wartość wprowadzi użytkownik uruchamiający kod.

Oto pierwszy przykład zasad bezpieczeństwa Rusta w akcji. W wielu niskopoziomowych językach programowania tego rodzaju test nie jest wykonywany, a skorzystanie z niepoprawnego indeksu może skutkować uzyskaniem dostępu do niewłaściwego bloku pamięci. Rust chroni przed takimi błędami. Zamiast pozwolić na uzyskanie dostępu do pamięci i kontynuację działania, zamyka program. Obsługę błędów w Ruście dokładniej omówimy w rozdziale 9. Tam też pokażemy jak pisać czytelny i bezpieczny kod, który nigdy nie panikuje i nie dopuszcza do nieprawidłowych dostępów do pamięci.

Funkcje

Funkcje są wszechobecne w kodzie Rusta. Widzieliśmy już jedną z najważniejszych funkcji w całym języku: funkcję main, która jest punktem wejściowym wielu programów. Widzieliśmy już też słowo kluczowe fn, za pomocą którego można deklarować nowe funkcje.

W kodzie Rusta konwencjonalnym stylem zapisu nazw funkcji i zmiennych jest użycie tzw. snake case. W tym stylu wszystkie człony pisane są małymi literami, a poszczególne wyrazy oddzielone są podkreślnikami. Poniżej program zawierający przykładową definicję funkcji:

Plik: src/main.rs

fn main() {
    println!("Witaj, świecie!");

    another_function();
}

fn another_function() {
    println!("Kolejna funkcja.");
}

Definicje funkcji w Ruście składają się ze słowa kluczowego fn, nazwy funkcji i pary nawiasów okrągłych. Nawiasy klamrowe informują kompilator, gdzie zaczyna i kończy się ciało funkcji.

Zdefiniowane przez nas funkcje możemy wywołać, pisząc ich nazwę wraz z parą nawiasów. Ponieważ funkcja another_function jest już zdefiniowana programie, możemy ją wywołać z wnętrza funkcji main. Proszę zauważyć, że definicja funkcji another_function znajduje się w kodzie źródłowym po ciele funkcji main; moglibyśmy równie dobrze umieścić ją przed funkcją main. Rusta nie obchodzi, gdzie umieszczasz definicje swoich funkcji, a jedynie to żeby te definicje były w zasięgu widzianym przez wywołującego.

Stwórzmy nowy projekt o nazwie functions, dzięki któremu zapoznamy się z głębiej z funkcjami w Ruście. Umieść powyższy przykład z another_function w pliku src/main.rs i uruchom program. Powinieneś zobaczyć taki wynik:

$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 0.28s
     Running `target/debug/functions`
Witaj, świecie!
Kolejna funkcja.

Linie kodu wykonywane są w kolejności, w jakiej pojawiają się w funkcji main. Najpierw pokaże się tekst „Witaj, świecie!”, a następnie wywołana jest funkcja another_function i ukazuje się wiadomość z jej wnętrza.

Parametry funkcji

Funkcje mogą również przyjmować parametry, które są specjalnymi zmiennymi, będącymi częścią sygnatury funkcji. Jeśli funkcja, którą wywołujesz, posiada parametry, możesz jej podać konkretne wartości tych parametrów. Technicznie rzecz biorąc, konkretne wartości przekazywane do funkcji nazywają się argumentami, jednak w swobodnych rozmowach ludzie mają w zwyczaju używać słów parametry i argumenty zamiennie, zarówno dla zmiennych w definicji funkcji, jak i konkretnych wartości przekazywanych podczas wywołania funkcji.

Poniższa zaktualizowana wersja funkcji another_function prezentuje, jak wyglądają parametry w Ruście:

Plik: src/main.rs

fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("Wartość x wynosi: {x}");
}

Spróbuj uruchomić ten program; powinieneś otrzymać następujący wynik:

$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 1.21s
     Running `target/debug/functions`
Wartość x wynosi: 5

Deklaracja funkcji another_function ma jeden parametr o nazwie x. Typ x jest określony jako i32. Kiedy wartość 5 jest przekazana do another_function, makro println! umieszcza 5 w miejscu, gdzie string formatujący zawiera x w nawiasach klamrowych.

W sygnaturze funkcji trzeba podać typ każdego z parametrów. To celowa decyzja projektantów Rusta: wymaganie adnotacji typów w definicjach funkcji powoduje, że nie trzeba już podawać ich niemal nigdzie więcej, a Rust i tak wie, co mamy na myśli. Kompilator jest również w stanie wypisać bardziej pomocne komunikaty o błędach, jeśli wie, jakich typów oczekuje funkcja.

Jeśli chcesz, żeby funkcja przyjmowała wiele parametrów, rozdziel kolejne deklaracje parametrów przecinkami, jak poniżej:

Plik: src/main.rs

fn main() {
    print_labeled_measurement(5, 'h');
}

fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("Wynik pomiaru: {value}{unit_label}");
}

W tym przykładzie stworzyliśmy funkcję print_labeled_measurement z dwoma parametrami. Pierwszy parametr ma nazwę value i typ i32. Drugi jest nazwany unit_label i jest typu char. Funkcja drukuje tekst zawierający wartości zarówno value jak i unit_label.

Spróbujmy uruchomić ten kod. Otwórz plik src/main.rs w twoim projekcie functions i zastąp jego zawartość kodem z powyższego przykładu. Uruchom program poleceniem 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`
Wynik pomiaru: 5h

Ponieważ wywołaliśmy tę funkcję z argumentem 5 jako wartość dla value oraz 'h' jako wartość dla unit_label, program wypisał właśnie te wartości.

Instrukcje i wyrażenia

Ciało funkcji jest składa sie z serii instrukcji (statements) i opcjonalnie jest zakończone wyrażeniem (expression). Jak dotąd analizowaliśmy jedynie funkcje bez końcowego wyrażenia, jednakże widziałeś już wyrażenia będące częścią instrukcji. Ponieważ Rust jest językiem opartym o wyrażenia, ważne jest, aby zrozumieć różnicę między tymi dwoma. Podobne rozróżnienie nie występuje w innych językach, więc przyjrzyjmy się teraz instrukcjom i wyrażeniom oraz jak różnice między nimi wpływają na postać funkcji.

  • Instrukcje to polecenia wykonania jakichś akcji; nie zwracają one wartości.
  • Wyrażenia zaś rozwijają się do wartości zwracanej. Spójrzmy na przykłady.

Tworzenie zmiennej i przypisanie do niej wartości z użyciem słowa kluczowego let jest instrukcją. W listingu 3-1, let y = 6; to instrukcja.

Plik: src/main.rs

fn main() {
    let y = 6;
}

Listing 3-1: Deklaracja funkcji main zawierającej jedną instrukcję

Definicje funkcji są również instrukcjami; cały powyższy przykład jest instrukcją sam w sobie.

Instrukcje nie mają wartości zwracanej. To znaczy, że nie możesz przypisać instrukcji let do innej zmiennej, tak jak poniższy kod próbuje zrobić; Rust zwróci błąd:

Plik: src/main.rs

fn main() {
    let x = (let y = 6);
}

Po uruchomieniu tego programu dostaniesz taki błąd:

$ 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

Instrukcja let y = 6 nie zwraca żadnej wartości, więc nie ma nic, co moglibyśmy przypisać do x. Tym Rust różni się od innych języków, takich jak C lub Ruby, w których operacja przypisania zwraca wartość tego przypisania. W tych językach można napisać x = y = 6 i zarówno x i y będą miały wartość 6; w Ruście tak się jednak nie stanie.

Wyrażenia rozwijają się do pewnej wartości i zaraz po instrukcjach stanowią większość kodu, jaki napiszesz w Ruście. Rozważmy prostą operację matematyczną, taką jak 5 + 6, która to jest wyrażeniem rozwijającym się do wartości 11. Wyrażenia mogą być częścią instrukcji: w listingu 3-1 liczba 6 w instrukcji let y = 6; jest wyrażeniem, które rozwija się do wartości 6. Wywołanie funkcji jest wyrażeniem. Wywołanie makra jest wyrażeniem. Blok, który tworzymy za pomocą nawiasów klamrowych dla zdefiniowania nowego zasięgu, również jest wyrażeniem, na przykład:

Plik: src/main.rs

fn main() {
    let y = {
        let x = 3;
        x + 1
    };

    println!("Wartość y wynosi: {y}");
}

To wyrażenie:

{
    let x = 3;
    x + 1
}

jest blokiem, który rozwija się do wartości 4. Ta wartość w ramach instrukcji let wpisywana jest do y. Zwróć uwagę na końcową linię x + 1 bez średnika, która różni się od większości linii, jakie widziałeś do tej pory. Wyrażenia nie kończą się średnikiem. Jeśli dodasz średnik na końcu wyrażenia, zmienisz je w instrukcję, która nie będzie rozwijać się do żadnej wartości. Pamiętaj o tym, gdy będziesz zagłębiać się w zagadnienie wartości zwracanych z funkcji i wyrażeń w kolejnej sekcji.

Funkcje zwracające wartość

Funkcje mogą zwracać wartości do miejsca w kodzie, gdzie zostały wywołane. Wartości zwracanej z funkcji nie nadajemy nazwy, a jedynie deklarujemy jej typ po strzałce (->). W Ruście wartość zwracana z funkcji jest równoważna wartości ostatniego wyrażenia z bloku ciała funkcji. Możesz też użyć instrukcji wcześniejszego wyjścia z funkcji poprzez użycie słowa kluczowego return, jednak większość funkcji zwraca niejawnie ostatnie wyrażenie. Poniżej przykład funkcji zwracającej wartość:

Plik: src/main.rs

fn five() -> i32 {
    5
}

fn main() {
    let x = five();

    println!("Wartość x wynosi: {x}");
}

W funkcji five nie ma żadnych wywołań funkcji, makr, ani nawet instrukcji let

  • tylko sama liczba 5. Jest to całkowicie poprawna funkcja w Ruście. Zauważ, że typ zwracany z funkcji jest również zdefiniowany, jako -> i32. Spróbuj uruchomić ten kod; rezultat powinien wyglądać tak:
$ cargo run
   Compiling functions v0.1.0 (file:///projects/functions)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/functions`
Wartość x wynosi: 5

W funkcji five 5 jest wartością zwracaną, dlatego też typ wartości zwracanej to i32. Przyjrzyjmy się temu bliżej. Są tu dwa istotne fragmenty: pierwszy, linia let x = five(); pokazuje, że używamy wartości zwracanej z funkcji five do zainicjalizowania zmiennej. Ponieważ funkcja five zwraca 5, to linia ta jest równoważna poniższej:

#![allow(unused)]
fn main() {
let x = 5;
}

Druga rzecz, to postać funkcji five, która nie przyjmuje żadnych parametrów i określa typ zwracany, ale jej ciało to samotne 5 bez średnika, ponieważ jest to wyrażenie, którego wartość chcemy zwrócić.

Spójrzmy na kolejny przykład:

Plik: src/main.rs

fn main() {
    let x = plus_one(5);

    println!("Wartość x wynosi: {x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1
}

Po uruchomieniu tego kodu na ekranie zostanie wypisane Wartość x wynosi: 6. Jednak gdybyśmy dopisali średnik po linii zawierającej x + 1, zmienilibyśmy wyrażenie w instrukcję i Rust zgłosiłby błąd.

Plik: src/main.rs

fn main() {
    let x = plus_one(5);

    println!("Wartość x wynosi: {x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1;
}

Próba kompilacji poskutkuje następującym błędem:

$ 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

Główny fragment wiadomości o błędzie, mismatched types, czyli niezgodność typów, informuje o podstawowym problemie w tym kodzie. Definicja funkcji plus_one określa typ zwracany jako i32, jednak instrukcje nie rozwijają się do żadnej wartości, i wartość zwrócona z funkcji przyjmuje postać (), czyli pustej krotki. Jest to sprzeczne z definicją funkcji i powoduje błąd. W komunikacie błędu Rust podaje przypuszczalne rozwiązanie tego problemu: sugeruje, aby usunąć średnik z końca linii, co naprawi błąd kompilacji.

Komentarze

Wszyscy programiści starają się tworzyć czytelny i zrozumiały kod, jednak czasem potrzebne jest dodatkowe wyjaśnienie. W takich wypadkach programiści umieszczają w kodzie notki lub komentarze, które mimo że są ignorowane przez kompilator, mogą okazać się przydatne dla osób czytających kod.

Oto prosty komentarz:

#![allow(unused)]
fn main() {
// Witaj, świecie
}

W Ruście, komentarze muszą rozpoczynać się dwoma ukośnikami i ciągną się do końca linii. W przypadku komentarzy, których długość przekracza jedną linię, musisz wstawić // na początku każdej linii, tak jak poniżej:

#![allow(unused)]
fn main() {
// A więc opisujemy tu coś skomplikowanego, wystarczająco długo,
// że potrzebujemy wieloliniowych komentarzy, aby to zrobić!
// Fiu! Fiu! Na szczęście ten komentarz wyjaśni, o co chodzi.
}

Komentarze mogą być też umieszczone na końcu linii zawierającej kod:

Plik: src/main.rs

fn main() {
    let lucky_number = 7; // Czuję, że sprzyja mi dziś szczęście
}

Jednak częściej spotkasz się z zapisem, w którym komentarz znajduje się w oddzielnej linii nad kodem, który jest przez niego opisywany:

Plik: src/main.rs

fn main() {
    // Czuję, że sprzyja mi dziś szczęście
    let lucky_number = 7;
}

Rust posiada też wbudowany inny typ komentarzy, komentarze dokumentacji, które omówimy w sekcji "Publikacja skrzyni w Crates.io" rozdziału 14.

Przepływ sterowania

Wykonanie jakiegoś kodu w zależności od tego, czy warunek jest spełniony, albo wykonywania go wielokrotnie dopóki warunek jest spełniony, to podstawowe możliwości większości języków programowania. Najpopularniejsze konstrukcje, które pozwalają sterować przebiegiem wykonania kodu Rusta to wyrażenia if oraz pętle.

Wyrażenia if

Wyrażenie if pozwala na rozgałęzienie kodu w zależności od spełnienia warunków. Podajemy warunek i nakazujemy: „Jeśli ten warunek jest spełniony, uruchom ten blok kodu. Jeśli warunek nie jest spełniony, nie uruchamiaj tego bloku kodu.”

Stwórzmy nowy projekt o nazwie branches (z ang. rozgałęzienia) w katalogu projects by zgłębić wyrażanie if. W pliku src/main.rs wpiszmy:

Plik: src/main.rs

fn main() {
    let number = 3;

    if number < 5 {
        println!("warunek został spełniony");
    } else {
        println!("warunek nie został spełniony");
    }
}

Wszystkie wyrażenia if rozpoczynają się słowem kluczowym if, po którym następuje warunek. W tym przypadku, warunek sprawdza czy zmienna number ma wartość mniejszą od 5. Blok kodu umieszczony w nawiasach klamrowych bezpośrednio po warunku zostanie wykonany tylko wtedy, gdy warunek będzie spełniony, tj. będzie miał wartość logiczną true. Bloki kodu powiązane z warunkami w wyrażenie if nazywane są czasami odnogami, podobnie jak to było w przypadku wyrażenia match, o którym wspomnieliśmy w sekcji „Porównywanie Odpowiedzi z Sekretnym Numerem” rozdziału 2.

Opcjonalnie, możemy również dodać wyrażenie else, co zresztą uczyniliśmy, aby dodać alternatywny blok kodu, wykonywany gdy warunek nie zajdzie (da false). Jeśli nie ma wyrażenia else, a warunek da false, program po prostu pominie blok if i przejdzie do następnego fragmentu kodu.

Spróbujmy uruchomić ten kod. Powinniśmy zobaczyć:

$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/branches`
warunek został spełniony

Zmieńmy number tak, by jego wartość nie spełniała warunku false i zobaczmy co się stanie:

fn main() {
    let number = 7;

    if number < 5 {
        println!("warunek został spełniony");
    } else {
        println!("warunek nie został spełniony");
    }
}

Uruchommy program ponownie i zobaczmy co wypisze:

$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/branches`
warunek nie został spełniony

Warto też zauważyć, że warunek w tym kodzie musi dawać wartość typu bool, bo inaczej kod się nie skompiluje. Na przykład, spróbujmy uruchomić następujący kod:

Plik: src/main.rs

fn main() {
    let number = 3;

    if number {
        println!("number wynosi trzy");
    }
}

Tutaj wartością warunku w if jest liczba 3, co prowadzi do błędu kompilacji:

$ 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

Błąd wskazuje, że Rust oczekiwał boola, a dostał liczbę. W przeciwieństwie do języków takich jak Ruby i JavaScript, Rust nie próbuje automatycznie konwertować typów nie-Boolean na Boolean. Jako warunek w if należy zawsze podać jawne wyrażenie dające wartość logiczną. Jeśli na przykład chcemy, aby blok kodu if uruchamiał się tylko wtedy, gdy liczba nie jest równa 0, to możemy zmienić wyrażenie if tak:

Plik: src/main.rs

fn main() {
    let number = 3;

    if number != 0 {
        println!("number wynosi coś innego niż zero");
    }
}

Ten program wypisze number wynosi coś innego niż zero.

Obsługa wielu warunków za pomocą else if

Można użyć wielu warunków łącząc if i else w wyrażenie else if. Na przykład:

Plik: src/main.rs

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number jest podzielny przez 4");
    } else if number % 3 == 0 {
        println!("number jest podzielny przez 3");
    } else if number % 2 == 0 {
        println!("number jest podzielny przez 2");
    } else {
        println!("number nie jest podzielny przez 4, 3, ani 2");
    }
}

Ten program może podążyć czterema różnymi ścieżkami. Po jego uruchomieniu powinniśmy zobaczyć:

$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/branches`
number jest podzielny przez 3

Kiedy ten program wykonuje się, sprawdza każde wyrażenie if po kolei i wykonuje pierwszy blok kodu, dla którego zachodzi warunek. Proszę zauważyć, że mimo iż 6 jest podzielne przez 2, nie widzimy wyjścia liczba jest podzielna przez 2, ani nie widzimy tekstu liczba nie jest podzielna przez 4, 3, ani 2 z bloku else. Dzieje się tak dlatego, że Rust wykonuje blok tylko dla pierwszego warunku dającego true, a gdy już go znajdzie, to dalszych warunków nawet nie sprawdza.

Użycie zbyt wielu wyrażeń else if może zagmatwać kod. Więc jeśli jest ich więcej niż jedno, to warto rozważyć refaktoryzację kodu. Dla takich przypadków, w Ruście przewidziano potężną konstrukcję match, która jest opisana w rozdziale 6.

if w składni let

Ponieważ if jest wyrażeniem, to możemy go użyć po prawej stronie instrukcji let, aby przypisać jego wynik do zmiennej, co pokazano na listingu 3-2.

Plik: src/main.rs

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("Wartość zmiennej number wynosi: {number}");
}

Listing 3-2: Przypisanie wyniku wyrażenia if do zmiennej

Zmiennej number zostanie nadana wartość będąca wynikiem wyrażenia if. Uruchommy ten kod, aby zobaczyć co się stanie:

$ cargo run
   Compiling branches v0.1.0 (file:///projects/branches)
    Finished dev [unoptimized + debuginfo] target(s) in 0.30s
     Running `target/debug/branches`
Wartość zmiennej number wynosi: 5

Należy pamiętać, że wartościami bloków kodu są ostatnie wyrażenie w nich zawarte, a liczby same w sobie są również wyrażeniami. W tym przypadku, wartość całego wyrażenia if zależy od tego, który blok kodu zostanie wykonany. Oznacza to, że wartości, które potencjalnie mogą być wynikami poszczególnych odnóg if muszą być tego samego typu. Na listingu 3-2, wynikami zarówno ramienia if jak i ramienia else były liczby całkowite i32. Jeśli typy są niezgodne, jak w poniższym przykładzie, to otrzymamy błąd:

Plik: src/main.rs

fn main() {
    let condition = true;

    let number = if condition { 5 } else { "six" };

    println!("Wartość zmiennej number wynosi: {number}");
}

Próba skompilowania tego kodu skończy się błędem. Odnogi if i else mają niezgodne typy wartości, zaś Rust dokładnie wskazuje, gdzie w programie należy szukać problemu:

$ 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

Wyrażenie w bloku if daje liczbę całkowitą, a wyrażenie w bloku else łańcuch znaków. To nie zadziała, ponieważ zmienne muszą mieć jeden typ, a Rust musi już w czasie kompilacji definitywnie wiedzieć jakiego typu jest zmienna number. Znajomość tego typu pozwala kompilatorowi sprawdzić, czy jest on poprawny we wszystkich miejscach użycia number. Rust nie byłby w stanie tego zrobić, gdyby typ number był określany dopiero w czasie wykonywania; kompilator byłby bardziej skomplikowany i dawałby mniej gwarancji na kod, gdyby musiał śledzić wiele hipotetycznych typów dla każdej zmiennej.

Powtarzanie Za Pomocą Pętli

Często przydaje się wykonanie bloku kodu więcej niż raz. Do tego zadania Rust udostępnia kilka pętli, które wykonują kod wewnątrz ciała pętli do końca, po czym natychmiast wykonują go ponownie. Aby poeksperymentować z pętlami, stwórzmy nowy projekt o nazwie loops.

Rust ma trzy rodzaje pętli: loop, while, i for. Wypróbujmy każdy z nich.

Powtarzanie Wykonania Za Pomocą loop

Słowo kluczowe loop nakazuje Rustowi wykonywać blok kodu w koło, bez końca, lub do momentu, w którym wyraźnie nakażemy mu przestać.

By to zilustrować, zmieńmy zawartość pliku src/main.rs w katalogu loops na następującą:

Plik: src/main.rs

fn main() {
    loop {
        println!("znowu!");
    }
}

Gdy uruchomimy ten program, zobaczymy znowu! wypisywane w koło, bez końca, dopóki ręcznie nie zatrzymamy programu. W większości terminali można to zrobić za pomocą skrótu klawiszowego ctrl-c. Spróbujmy:

$ cargo run
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished dev [unoptimized + debuginfo] target(s) in 0.29s
     Running `target/debug/loops`
znowu!
znowu!
znowu!
znowu!
^Cznowu!

Symbol ^C pokazuje gdzie wcisnęliśmy ctrl-c. Słowo znowu! może zostać wypisane lub nie po ^C, zależnie od tego, która linia programu była wykonywana w momencie gdy odebrał on sygnał przerwania.

Szczęśliwie, Rust zapewnia również sposób na przerwanie pętli za pomocą kodu. Można umieścić słowo kluczowe break wewnątrz pętli, aby powiedzieć programowi, gdzie ma przerwać jej wykonywanie. Proszę sobie przypomnieć, że już to zrobiliśmy w grze-zgadywance w sekcji „Quitting After a Correct Guess” rozdziału 2, aby zakończyć program, gdy użytkownik wygrał grę, zgadując poprawną liczbę.

W grze-zgadywance użyliśmy również continue, które, użyte w pętli, nakazuje programowi pominąć kod pozostały do wykonania w bieżącej iteracji i rozpocząć następną iterację.

Zwracanie Wartości z Pętli

Jednym z zastosowań pętli loop jest ponawianie prób operacji, która może się nie udać, jak na przykład sprawdzenie czy wątek zakończył swoją pracę. Może zajść również potrzeba przekazania wyniku tej operacji poza pętlę, do reszty kodu. Aby to zrobić, można ten wynik podać bezpośrednio po wyrażeniu break zatrzymującym pętle. Zostanie on zwrócony na zewnątrz pętli i będzie można go tam użyć, na przykład tak:

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("Zmienna result wynosi {result}");
}

Przed pętlą deklarujemy zmienną o nazwie counter i inicjujemy ją wartością 0. Następnie deklarujemy zmienną o nazwie result, która będzie przechowywać wartość zwracaną z pętli. W każdej iteracji pętli dodajemy 1 do zmiennej counter i, następnie, sprawdzamy czy counter jest równy 10. Jeśli jest, to używamy słowa kluczowego break z wartością counter * 2. Za pętlą umieściliśmy średnik kończący instrukcję przypisującą tą wartość do result. Na koniec wypisujemy wartość result, która w tym przypadku wynosi 20.

Etykiety Rozróżniające Pętle

Gdy zagnieżdżamy pętle w pętlach, break i continue odnoszą się do najbardziej wewnętrznej pętli, w której się znajdują. Można opcjonalnie określić etykietę dla pętli, której można następnie użyć z break lub continue, by wskazać, że odnoszą się one do wskazanej pętli zamiast najbardziej zagnieżdżonej. Etykiety pętli zaczynają się znakiem pojedynczego cytatu. Oto przykład:

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}");
}

Pętla zewnętrzna ma etykietę counting_up i liczy w górę od 0 do 2. Wewnętrzna pętla bez etykiety odlicza w dół od 10 do 9. Pierwszy break, bez etykiety, zakończy tylko wewnętrzną pętlę. Instrukcja break 'counting_up; wyjdzie z pętli zewnętrznej. Ten kod drukuje:

$ 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

Pętla Warunkowa while

Program często potrzebuje sprawdzić warunek wewnątrz pętli. Pętla działa tak długa jak warunek daje true. Gdy warunek przestaje dawać true, program wywołuje break, zatrzymując pętlę. Można zaimplementować takie zachowania za pomocą kombinacji loop, if, else i break; zachęcam do spróbowania. Jednak jest ono na tyle powszechne, że Rust ma dla niego wbudowaną konstrukcję językową, zwaną pętlą while. Program z listingu 3-3 wykonuje trzy iteracje za pomocą pętli while, odliczając za każdym razem, a następnie, po zakończeniu pętli, drukuje komunikat i wychodzi.

Plik: src/main.rs

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");

        number -= 1;
    }

    println!("LIFTOFF!!!");
}

Listing 3-3: Użycie pętli while by wykonywać kod dopóki zachodzi warunek

Taka konstrukcja eliminuje wiele zagnieżdżeń, które byłyby konieczne w przypadku użycia loop, if, else i break, równocześnie poprawiając czytelność. Pętla się wykonuje tak długo jak warunek daje true.

Przechodzenie Po Kolekcji Za Pomocą for

Do przejścia po kolekcji, takiej jak tablica, można użyć pętli while. Na przykład, pętla na listingu 3-4 wypisuje każdy element tablicy a.

Plik: src/main.rs

fn main() {
    let a = [10, 20, 30, 40, 50];
    let mut index = 0;

    while index < 5 {
        println!("wartość wynosi: {}", a[index]);

        index += 1;
    }
}

Listing 3-4: Przechodzenie po każdym elemencie kolekcji za pomocą pętli while

Ten kod liczy w górę po elementach tablicy. Rozpoczyna od indeksu 0 i wykonuje pętle aż do osiągnięcia ostatniego indeksu tablicy, tj. do momentu gdy index < 5 przestaje dawać true. Uruchomienie tego kodu spowoduje wydrukowanie każdego elementu tablicy:

$ cargo run
   Compiling loops v0.1.0 (file:///projects/loops)
    Finished dev [unoptimized + debuginfo] target(s) in 0.32s
     Running `target/debug/loops`
wartość wynosi: 10
wartość wynosi: 20
wartość wynosi: 30
wartość wynosi: 40
wartość wynosi: 50

Wszystkie pięć wartości zawartych w tablicy pojawia się w terminalu, zgodnie z oczekiwaniami. Nawet jeśli index osiągnie w pewnym momencie wartość 5, pętla zatrzymuje się przed próbą pobrania z tablicy szóstej wartości.

Jednakże to rozwiązanie jest podatne na błędy; program może spanikować, jeśli indeks lub warunek będzie nieprawidłowy. Na przykład, jeśli skócimy tablicę a do czterech elementów, zapominając przy tym zaktualizować warunek na while index < 4, kod spanikuje. To rozwiązanie może być również powolne, ponieważ kompilator może dodać kod sprawdzający, w każdej iteracji pętli, czy indeks znajduje się w granicach tablicy.

Zwięźlejszą alternatywą jest pętla for wykonująca jakiś kod dla każdego elementu w kolekcji. Listing 3-5 pokazuje przykład jej użycia.

Plik: src/main.rs

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a.iter() {
        println!("wartość wynosi: {element}");
    }
}

Listing 3-5: Przechodzenie po każdym elemencie kolekcji za pomocą pętli for

Ten kod daje takie same wyjście jak ten na listingu 3-4. Co ważne, zwiększyliśmy bezpieczeństwo kodu i wyeliminowaliśmy zagrożenie wystąpienie błędów związanych z przekroczeniem końca tablicy albo niedojściem do niego i w konsekwencji nieosiągnięciem niektórych elementów.

W przeciwieństwie do metody użytej na listingu 3-4, korzystając z pętli for nie musimy martwić się poprawianiem innego kodu gdy zmieniamy liczbę elementów w tablicy.

Bezpieczeństwo i zwięzłość pętli for sprawiają, że jest ona najczęściej wykorzystywaną pętlą w Rust. Nawet gdy istnieje potrzeba wykonania jakiegoś kod określoną liczbę razy, jak w przykładzie odliczania, który na listingu 3-3 używał pętli while, większość rustowców użyłaby pętli for wraz z zawartym w bibliotece standardowej Range (z ang. zakres), który generuje wszystkie liczby w kolejności, zaczynając od jednej liczby i kończąc przed inną liczbą.

Oto jak wyglądałoby odliczanie przy użyciu pętli for i metody rev (o której jeszcze nie mówiliśmy) odwracającej zakres:

Plik: src/main.rs

fn main() {
    for number in (1..4).rev() {
        println!("{number}!");
    }
    println!("LIFTOFF!!!");
}

Ten kod jest nieco ładniejszy, nieprawdaż?

Podsumowanie

Udało się! To był długi rozdział: poznaliśmy zmienne, skalarne i złożone typy danych, funkcje, komentarze, wyrażenia if i pętle! Aby przećwiczyć pojęcia omawiane w tym rozdziale, spróbuj zbudować programy wykonujące następujące czynności:

  • Przeliczanie temperatur pomiędzy stopniami Celsjusza i Fahrenheita.
  • Generowanie n-tej liczby ciągu Fibonacciego.
  • Drukowanie tekstu kolędy "The Twelve Days of Christmas" z wykorzystaniem powtórzeń w piosence.

Kiedy będziesz gotowy aby przejść dalej, porozmawiamy o koncepcji Rusta, która nie jest powszechna w innych językach programowania, o własności.

Zrozumienie systemu własności

System własności (ownership) jest najbardziej unikalną cechą Rusta, która pozwala zagwarantować bezpieczeństwo pamięci bez konieczności użycia automatycznego systemu odśmiecania (garbage collector). Zrozumienie, jak w Ruście funkcjonuje ten mechanizm jest zatem niezwykle istotne. W niniejszym rozdziale będziemy rozmawiać o własności oraz kilku powiązanych z nią funkcjonalnościach: pożyczaniu, wycinkach, a także o tym, jak Rust rozmieszcza dane w pamięci.

Czym jest własność?

Własność to zestaw reguł, które determinują, jak program Rusta zarządza pamięcią. Wszystkie programy muszą kontrolować sposób wykorzystywania pamięci komputera podczas swojego działania. Niektóre języki korzystają z automatycznego systemu odśmiecania (garbage collection), który regularnie poszukuje fragmentów pamięci, których działający program już nie używa. W innych językach, sam programista ręcznie zajmuje i zwalnia pamięć. Rust wykorzystuje trzecie podejście: pamięć jest zarządzana przez system własności, obejmujący zestaw zasad sprawdzanych przez kompilator w trakcie kompilacji. Jeśli którakolwiek z reguł zostanie naruszona, program nie skompiluje się. Jednocześnie żaden z aspektów związanych z systemem własności nie spowalnia działania programu.

Ponieważ własność jest nowym pojęciem dla wielu programistów, przyzwyczajenie się do niej zabiera trochę czasu. Dobra wiadomość jest taka, że w miarę nabywania doświadczenia z Rustem i zasadami systemu własności, rośnie też twoja zdolność do naturalnego tworzenia bezpiecznego i wydajnego kodu. Tak trzymaj!

Kiedy zrozumiesz system własności, będziesz mieć solidną podstawę ku zrozumieniu innych, unikatowych funkcjonalności Rusta. W tym rozdziale nauczysz się, czym jest własność za pomocą kilku przykładów, które skupiają się na bardzo często spotykanej strukturze danych: łańcuchach znaków (string).

Stos i sterta

W wielu językach programowania nie trzeba zbyt często myśleć o stosie i o stercie. Ale w przypadku języka systemowego takiego jak Rust, to, czy zmienna zapisana jest na stosie czy na stercie, ma wpływ na zachowanie całego języka i określa, dlaczego należy podjąć niektóre decyzje. W dalszej części rozdziału opiszemy części systemu własności w odniesieniu do stosu i sterty, zaczynamy więc od krótkiego, przygotowawczego wyjaśnienia.

Zarówno stos jak i sterta są częściami pamięci dostępnymi dla programu w trakcie działania, ale charakteryzują się one odmienną strukturą. Stos przechowuje dane w takiej kolejności, w jakiej tam trafiają, a usuwane są z niego w kolejności odwrotnej. Działanie te określa się nazwą last in, first out (ostatni na wejściu, pierwszy na wyjściu). Pomyśl o stosie talerzy: kiedy kładziesz na nim nowe talerze, umieszczasz je na szczycie stosu, a kiedy jest ci jakiś potrzebny, zdejmujesz go ze szczytu. Dodawanie lub usuwanie talerzy ze środka lub ze spodu stosu nie jest już takie łatwe. Dodawanie danych nosi nazwę odkładania na stos (pushing onto the stack), a usuwanie ich nazywane jest zdejmowaniem ze stosu (popping off the stack).

Każda dana umieszczona na stosie musi mieć znany, stały rozmiar. Dane, których rozmiar jest nieznany na etapie kompilacji lub może ulegać zmianie, muszą być przechowywane na stercie. Sterta jest mniej zorganizowana: kiedy coś się na niej umieszcza, należy poprosić o przydzielenie pewnego jej obszaru. Alokator pamięci znajduje na stercie wolne, wystarczająco duże miejsce, oznacza je jako będące w użyciu i zwraca wskaźnik zawierający adres wybranej lokalizacji. Proces ten nazywamy alokacją na stercie lub po prostu alokacją. Umieszanie danych na stosie nie jest uznawane za alokację. Ze względu na to, że zwrócony wskaźnik posiada znany, ustalony rozmiar, możemy przechować go na stosie. Jednak gdy chcemy dostać się do właściwych danych, musimy podążyć za wskaźnikiem.

Pomyśl o byciu rozsadzanym w restauracji. Przy wejściu podajesz ilość osób w swojej grupie, a pracownik znajduje pusty stolik, przy którym wszyscy się pomieszczą i prowadzi ich na miejsce. Jeśli ktoś z twojej grupy sie spóźni, aby was znaleźć, może zapytać, gdzie was posadzono.

Odkładanie na stosie jest szybsze od alokacji na stercie, ponieważ alokator nigdy nie musi szukać miejsca na dodanie nowych danych; to miejsce znajduje się zawsze na szczycie stosu. Alokacja na stercie natomiast wymaga więcej pracy, ponieważ system operacyjny musi w pierwszej kolejności znaleźć wystarczająco dużo miejsca, aby dane się zmieściły. a następnie przeprowadzić niezbędne operacje, by przygotować się na następną alokację.

Dostęp do danych na stercie jest wolniejszy od dostępu do danych na stosie, ponieważ należy je zlokalizować korzystając ze wskaźnika. Nowoczesne procesory działają szybciej, jeżeli nie muszą dużo skakać po pamięci. Kontynuując analogię, załóżmy, że kelner w restauracji zbiera zamówienia z wielu stolików. Bardziej wydajne jest zebranie wszystkich zamówień z jednego stolika, zanim przejdzie się do kolejnego. Zebranie pojedynczego zamówienia ze stolika A, następnie jednego ze stolika B, kolejnrgo znów ze stolika A i powtórnie ze stolika B, byłoby zdecydowanie wolniejszym procesem. Z tego samego względu, procesor wykonuje swoje zadanie lepiej, operując na danych sąsiadujących z innymi danymi (jak ma to miejsce na stosie), niż gdyby operował na danych oddalonych od siebie (co może się zdarzyć w przypadku sterty). Alokacja sporego obszaru pamięci na stercie również może potrwać.

Kiedy twój kod wywołuje funkcję, przekazywane do niej argumenty (łącznie z potencjalnymi wskaźnikami do danych na stercie) oraz jej wewnętrzne zmienne są odkładane na stosie. Gdy funkcja się kończy, wartości te są zdejmowane ze stosu.

Do problemów, którym przeciwstawia się system własności, należą: śledzenie, które fragmenty kodu używają których danych na stercie, minimalizowanie duplikowania się danych na stercie, a także pozbywanie się ze sterty nieużywanych danych, celem uniknięcia wyczerpania się pamięci. Po zrozumieniu pojęcia własności, nie będziesz juz musiał zbyt często myśleć o stosie czy o stercie. Jednak świadomość tego, że zawiadowanie danymi na stercie jest istotą istnienia systemu własności, pomaga wyjaśnić, dlaczego działa on tak, jak działa.

Zasady systemu własności

W pierwszej kolejności przyjrzyjmy się zasadom systemu własności. Proszę mieć je na uwadze, kiedy będziemy omawiać ilustrujące je przykłady:

  • Każda wartość w Ruście ma właściciela.
  • W danym momencie może istnieć tylko jeden właściciel.
  • Kiedy sterowanie wychodzi poza zasięg właściciela, wartość zostaje zwolniona.

Zasięg zmiennych

Teraz, kiedy znamy już podstawy składni, nie będziemy umieszczać w treści przykładów kodu fn main() {. Jeśli zatem przepisujesz kod na bieżąco, musisz ręcznie umieszczać zaprezentowane dalej fragmenty wewnątrz funkcji main. Dzięki temu, przykłady będą nieco bardziej zwięzłe, pozwalając nam skupić się na istocie sprawy zamiast na powtarzalnych frazach.

W pierwszym przykładzie systemu własności, przyjrzymy się zasięgowi kilku zmiennych. Zasięgiem elementu nazywamy obszar programu, wewnątrz którego dany element zachowuje ważność (istnieje). Powiedzmy, że mamy zmienną, która wygląda tak:

#![allow(unused)]
fn main() {
let s = "witaj";
}

Zmienna s odnosi się do literału łańcuchowego, którego wartość jest ustalona w samym kodzie programu. Zmienna zachowuje ważność od miejsca, w którym ją zadeklarowano, do końca bieżącego zasięgu. Listing 4-1 zawiera komentarze wyjaśniające, gdzie zmienna s zachowuje ważność.

fn main() {
    {
                           // s nie ma tu jeszcze ważności - jeszcze jej nie zadeklarowano
        let s = "witaj";   // od tego momentu s ma ważność

        // jakieś operacje na s
    }                           // bieżący zasięg się kończy - s traci ważność
}

Listing 4-1: Zmienna, oraz zasięg, w którym zachowuje ona ważność

Innymi słowy, mamy do czynienia z dwoma istotnymi momentami w czasie:

  • Kiedy zmienna s wchodzi w zasięg, zyskuje ważność.
  • Zmienna pozostaje ważna, dopóki nie wyjdzie z zasięgu.

Na tę chwilę zależność między zasięgiem a ważnością zmiennych jest podobna do sytuacji w innych językach programowania. Posłużymy się tą wiedzą, wprowadzając nowy typ danych: String (łańcuch znaków).

Typ String

Aby zilustrować zasady systemu własności, potrzebujemy typu danych, który jest bardziej złożony od tych, które omawiane były w sekcji „Typy danych” rozdziału 3. Wszystkie opisane tam typy przechowywane są na stosie i są z niego zdejmowane, kiedy skończy się ich zasięg. Potrzebny jest nam natomiast typ przechowujący zawarte w nim dane na stercie. Dowiemy się wówczas, skąd Rust wie, kiedy te dane usunąć.

W przykładzie użyjemy typu String, koncentrując się na tych jego elementach, które odnoszą się do systemu własności. Te same elementy mają znaczenie dla innych złożonych typów, które dostarcza biblioteka standardowa oraz tych, które stworzysz sam. Typ String omawiany będzie dogłębnie w rozdziale 8.

Widzieliśmy już literały łańcuchowe, których dane na stałe umieszczone są w treści programu. Takie zmienne są wygodne w użyciu, ale nieprzydatne w wielu sytuacjach, w których używa się danych tekstowych. Jednym z powodów jest to, że są one niemodyfikowalne. Innym, że nie każda zawartość łańcucha tekstowego jest znana podczas pisania programu. Na przykład: co zrobić, jeśli chcemy pobrać dane od użytkownika i je przechować? Dla takich sytuacji Rust przewiduje drugi typ łańcuchowy: String. Typ ten alokowany jest na stercie i z tego względu może przechowywać dane, których ilość jest nieznana podczas kompilacji. Można przekształcić niemodyfikowalny literał łańcuchowy w zmienną typu String za pomocą funkcji from. Wygląda to tak:

#![allow(unused)]
fn main() {
let s = String::from("witaj");
}

Podwójny dwukropek :: jest operatorem umożliwiającym wykorzystanie funkcji from z przestrzeni nazw typu String, zamiast konieczności utworzenia ogólnej funkcji o przykładowej nazwie string_from. Ten rodzaj składni będzie szerzej omawiany w sekcji „Składnia metod” w rozdziale 5 oraz podczas rozważań o przestrzeniach nazw modułów w sekcji „Ścieżki odnoszenia się do elementów w hierarchii modułów” w rozdziale 7.

Ten rodzaj łańcucha znaków można modyfikować:

fn main() {
    let mut s = String::from("witaj");

    s.push_str(", świecie!"); // push_str() dodaje literał do zmiennej String

    println!("{}", s); // To spowoduje wyświetlenie tekstu: `hello, world!`
}

Jaka jest zatem różnica? Dlaczego String może być modyfikowalny, a literał nie? Różnica polega na sposobie, w jakim oba te typy korzystają z pamięci.

Pamięć i alokacja

W przypadku literału łańcuchowego, jego wartość znana jest już w czasie kompilacji, więc przechowywany tekst jest na stałe zakodowany w docelowym pliku wykonywalnym, co czyni literały szybkimi i wydajnymi. Ale cechy te wynikają z niemodyfikowalności literałów. Niestety, nie możemy w pliku binarnym umieścić bańki pamięci pod każdy potrzebny tekst, którego rozmiar jest nieznany podczas kompilacji i może się zmienić w trakcie działania programu.

Mając typ String, w celu obsługi modyfikowalnego i potencjalnie rosnącego tekstu, musimy zaalokować pewną ilość pamięci na stercie, nieznaną podczas kompilacji. To oznacza, że:

  • O przydział pamięci należy poprosić alokator w trakcie wykonywania programu.
  • Potrzebny jest sposób na oddanie pamięci do alokatora, kiedy String nie będzie już potrzebny.

Pierwszą część robimy sami, wywołując funkcję String::from, której implementacja zawiera prośbę o wymaganą pamięć. Podobne rozwiązanie jest w w wielu innych językach programowania.

Druga część znacznie się za to różni. W językach wyposażonych w systemy odśmiecania (garbage collector - GC), GC śledzi i zwalnia pamięć, która nie jest już używana, a my nie musimy już o tym myśleć. W językach pozbawionych GC, naszą odpowiedzialnością jest identyfikowanie nieużywanej już pamięci i bezpośrednie wywoływanie zarówno kodu, który tę pamięć zwalnia, jak i tego, który ją alokuje. Poprawne wykonanie tej operacji stanowiło historycznie trudny, programistyczny problem. Jeśli zapomnimy, marnujemy pamięć. Jeśli zrobimy to za wcześnie, zostaniemy z unieważnioną zmienną. Zrobimy to dwukrotnie - to też błąd. Musimy połączyć w pary dokładnie jedną alokację z dokładnie jednym zwolnieniem.

Rust prezentuje inne podejście: pamięć jest automatycznie zwalniana, kiedy skończy się zasięg zmiennej będącej jej właścicielem. Oto wersja naszego przykładu z listingu 4-1, który używa typu String zamiast literału:

fn main() {
    {
        let s = String::from("witaj"); // s ma ważność od tego momentu

        // jakieś operacje na s
    }                                  // bieżący zasięg się kończy - s traci
                                       // ważność
}

Istnieje naturalny moment, w którym można oddać pamięć wykorzystywaną przez nasz String do alokatora - kiedy kończy się zasięg zmiennej s. Kiedy zasięg jakiejś zmiennej się kończy, Rust wywołuje za nas specjalną funkcję. Funkcja ta nosi nazwę drop (porzuć, upuść), a w jej treści autor typu String umieścił kod zwalniający pamięć. Funkcja drop zostaje wywołana przez Rusta automatycznie, przy klamrze zamykającej.

Uwaga: W C++ schemat dealokacji zasobów przy końcu czasu życia jakiegoś elementu jest czasem nazywany Inicjowaniem Przy Pozyskaniu Zasobu (Resource Acquisition Is Initialization (RAII)). Funkcja drop z Rusta może wydać się znajoma osobom, które miały styczność ze schematami RAII.

Schemat ten ma ogromny wpływ na sposób pisania kodu w Ruście. Na tym etapie może wydawać się to proste, ale program może zachować się niespodziewanie w bardziej złożonych przypadkach, kiedy chcemy, aby kilka zmiennych używało tej samej danej, alokowanej na stercie. Zbadajmy teraz kilka takich sytuacji.

Przenoszenie Zmiennych i Danych

Kilka zmiennych może w Ruście odnosić się do tej samej danej na różne sposoby. Spójrzmy na przykład w listingu 4-2, z wykorzystaniem liczby całkowitej:

fn main() {
    let x = 5;
    let y = x;
}

Listing 4-2: Przypisanie całkowitej wartości zmiennej x do zmiennej y

Z całą pewnością możemy odgadnąć, co ten kod robi: „przypisuje 5 do x, a następnie wykonuje kopię wartości przechowywanej w x i przypisuje ją do y.”. Mamy teraz dwie zmienne: x i y, obie o wartości 5. Dzieje się dokładnie tak, ponieważ liczby całkowite są prostymi wartościami o stałym rozmiarze, więc obie wartości 5 zostają odłożone na stos.

Teraz przyjrzyjmy się wersji z typem String:

fn main() {
    let s1 = String::from("witaj");
    let s2 = s1;
}

Wygląda to bardzo podobnie do wcześniejszego kodu, więc możemy zakładać, że jego działanie też będzie podobne: w drugiej linii powstaje kopia wartości w s1 i zostaje ona przypisana do s2. Ale tak się akurat nie dzieje.

Rysunek 4-1 objaśnia, co dzieje się we wnętrzu typu String. Typ String składa się z trzech części, pokazanych po lewej stronie. Są to: wskaźnik do pamięci przechowującej właściwy łańcuch znaków, znacznik jego długości (length) i dane o ilości pamięci dostępnej dla danego ciągu (capacity). Ta grupa danych przechowywana jest na stosie. Po prawej pokazano obszar pamięci na stercie, który zawiera tekst.

Two tables: the first table contains the representation of s1 on the
stack, consisting of its length (5), capacity (5), and a pointer to the first
value in the second table. The second table contains the representation of the
string data on the heap, byte by byte.

Rysunek 4-1: Reprezentacja pamięci dla typu String przechowującego wartość "witaj" przypisaną do s1

Length (długość) wskazuje, ile bajtów pamięci zajmuje bieżący ciąg znaków w zmiennej typu String, natomiast capacity (pojemność) przechowuje dane o całkowitej ilości pamięci, jaką alokator dla tej zmiennej przydzielił. Różnica między długością i pojemnością ma znaczenie, ale nie w tym kontekście. Dlatego na razie możemy zignorować pojemność.

Kiedy przypisujemy s1 do s2, dane ze zmiennej typu String zostają skopiowane. Dotyczy to przechowywanych na stosie: wskaźnika, długości i pojemności. Dane tekstowe, do których odnosi się wskaźnik nie są kopiowane. Innymi słowy, reprezentację pamięci w tej sytuacji ilustruje Rysunek 4-2.

Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap.

Rysunek 4-2: Reprezentacja w pamięci zmiennej s2 posiadającej kopię wskaźnika i znaczników długości i pojemności zmiennej s1

Rysunek 4-3 ukazuje nieprawdziwą reprezentację pamięci, w której Rust również skopiował dane na stercie. Gdyby taka sytuacja miała miejsce, operacja s2 = s1 mogłaby potencjalnie zająć dużo czasu, w przypadku sporej ilości danych na stercie.

Cztery tabele: dwie tabele reprezentują dane trzymane na stosie przez s1 i s2,
i każda wskazuje na swoją własną kopię łańcucha na stercie.

Rysunek 4-3: Hipotetyczny wynik operacji s2 = s1, gdyby Rust również kopiował dane sterty

Wcześniej powiedzieliśmy, że kiedy zasięg zmiennej się kończy, Rust wywołuje automatycznie funkcję drop i zwalnia obszar na stercie dla tej zmiennej. Ale na Rysunku 4-2 przedstawiono sytuację, w której oba wskaźniki wskazują na ten sam obszar. Jest to problematyczne: kiedy zasięg s2 i s1 się skończy, nastąpi próba dwukrotnego zwolnienia tej samej pamięci. Sytuacja ta jest znana jako błąd podwójnego zwolnienia i należy do grupy bugów bezpieczeństwa pamięci, o których wcześniej wspomnieliśmy. Podwójne zwalnianie pamięci może prowadzić do jej zepsucia, a w efekcie do potencjalnych luk bezpieczeństwa.

Aby zapewnić bezpieczeństwo pamięci, po linii let s2 = s1;, zamiast próbować skopiować zaalokowaną pamięć, Rust traktuje zmienną s1 jako unieważnioną i, tym samym, nie musi nic zwalniać, kiedy zasięg s1 się kończy. Zobaczmy, co stanie się przy próbie użycia zmiennej s1 po utworzeniu zmiennej s2. Próba się nie powiedzie:

fn main() {
    let s1 = String::from("witaj");
    let s2 = s1;

    println!("{}, świecie!", s1);
}

Rust zwróci poniższy błąd, ponieważ nie zezwala na odnoszenie się do elementów przy użyciu unieważnionych zmiennych:

$ 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("witaj");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = s1;
  |              -- value moved here
4 |
5 |     println!("{}, świecie!", 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

Jeśli słyszałeś terminy „płytka kopia” oraz „głęboka kopia” pracując z innymi językami, to z pewnością wiesz, że skopiowanie wskaźnika ze znacznikami długości i pojemności, ale bez kopiowania danych, przypomina tworzenie płytkiej kopii. Ale ponieważ Rust jednocześnie unieważnia źródłową zmienną, zamiast nazywać taki proces płytką kopią, używa się terminu przeniesienie. W tym przypadku moglibyśmy powiedzieć, że zmienna s1 została przeniesiona do s2. Rysunek 4-4 ilustruje, co tak naprawdę dzieje się w pamięci.

Three tables: tables s1 and s2 representing those strings on the
stack, respectively, and both pointing to the same string data on the heap.
Table s1 is grayed out be-cause s1 is no longer valid; only s2 can be used to
access the heap data.

Rysunek 4-4: Reprezentacja w pamięci po unieważnieniu zmiennej s1

To rozwiązuje nasz problem! Jeśli jedynie zmienna s2 zachowuje ważność, to w momencie wyjścia z zasięgu, jako jedyna zwolni zajmowaną pamięć i po sprawie.

Dodatkowo, implikuje to decyzję w budowie języka: Rust nigdy automatycznie nie tworzy „głębokich” kopii twoich danych. Można zatem założyć, że automatyczny proces kopiowania nie będzie drogą operacją w sensie czasu jej trwania.

Klonowanie zmiennych i danych

W przypadku gdy chcemy wykonać głęboką kopię danych ze sterty dla typu String, a nie tylko danych ze stosu, możemy skorzystać z często stosowanej metody o nazwie clone (klonuj). Składnia metod będzie omawiana w rozdziale 5, ale ponieważ metody są popularnymi funkcjonalnościami wielu języków, zapewne już je wcześniej widziałeś.

Oto przykład działania metody clone:

fn main() {
    let s1 = String::from("witaj");
    let s2 = s1.clone();

    println!("s1 = {}, s2 = {}", s1, s2);
}

Ten przykład działa bez problemu i ilustruje on celowe odtworzenie zachowania pokazanego na Rysunku 4-3, na którym dane ze sterty kopiowane.

Kiedy widzisz odwołanie do metody clone, możesz się spodziewać, że wykonywana operacja będzie kosztowna czasowo.

Dane przechowywane wyłącznie na stosie: Copy (kopiowanie)

Jest jeszcze jeden szczegół, którego nie omówiliśmy. Kod korzystający z liczb całkowitych, którego treść pokazano na listingu 4-2, działa i jest prawidłowy:

fn main() {
    let x = 5;
    let y = x;

    println!("x = {}, y = {}", x, y);
}

Zdaje się on przeczyć temu, czego przed chwilą się nauczyliśmy: nie mamy wywołania clone, ale zmienna x zachowuje ważność i nie zostaje przeniesiona do y.

Przyczyną jest to, że typy takie jak liczby całkowite, które mają znany rozmiar już podczas kompilacji, są w całości przechowywane na stosie. Tworzenie kopii ich wartości jest więc szybkie. To oznacza, że nie ma powodu unieważniać zmiennej x po stworzeniu zmiennej y. Innymi słowy, w tym wypadku nie ma różnicy między głęboką i płytką kopią, więc wywołanie metody clone nie różniłoby się od zwykłego płytkiego kopiowania i można je zatem pominąć.

Rust zawiera specjalną adnotację zwaną „cechą Copy”, którą można zaimplementować dla typów przechowywanych na stosie, takich jak liczby całkowite (więcej o cechach będzie w rozdziale 10). Jeśli dany typ ma zaimplementowaną cechę Copy, zmienną, którą przypisano do innej zmiennej, można dalej używać.

Rust nie pozwoli dodać adnotacji Copy do żadnego typu, dla którego zaimplementowano (lub zaimplementowano dla jakiejkolwiek jego części tego typu) cechę Drop. Jeśli typ wymaga wykonania konkretnych operacji po tym, jak reprezentującej go zmiennej kończy się zasięg, a dodamy dla tego typu cechę Copy, uzyskamy błąd kompilacji. Aby nauczyć się, jak implementować cechę Copy dla danego typu, zajrzyj do „Cechy wyprowadzalne” w Dodatku C.

Które więc typy mają cechę Copy? Dla danego typu można dla pewności sprawdzić w dokumentacji, ale jako regułę zapamiętaj, że każda grupa wartości skalarnych może mieć cechę Copy i nic, co wymaga alokacji lub jest pewnego rodzaju zasobem jej nie ma. Oto przykłady typów z zaimplementowaną cechą Copy:

  • Wszystkie typy całkowite, takie jak u32.
  • Typ logiczny, bool, z wartościami true oraz false.
  • Wszystkie typy zmiennoprzecinkowe, jak f64.
  • Typ znakowy, char.
  • Krotki, jeśli zawierają wyłącznie typy z cechą Copy. Na przykład, (i32, i32) ma cechę Copy, ale (i32, String) już nie.

Własność i funkcje

Mechanika przekazywania wartości do funkcji jest podobna do przypisania wartości do zmiennej. Przekazanie zmiennej do funkcji przeniesie ją lub skopiuje, tak jak przy przypisywaniu. Listing 4-3 ukazuje przykład z kilkoma adnotacjami ilustrującymi, kiedy zaczynają się lub kończą zasięgi zmiennych:

Plik: src/main.rs

fn main() {
	let s = String::from("witaj");       // s pojawia się w zasięgu

	bierze_na_wlasnosc(s);      // Wartość zmiennej s przenosi się do funkcji...
	// ...i w tym miejscu zmienna jest unieważniona.

	let x = 5;                      // Zaczyna się zasięg zmiennej x.

	robi_kopie(x);           // Wartość x przeniosłaby się do funkcji, ale
	// typ i32 ma cechę Copy, więc w dalszym ciągu
	// można używać zmiennej x.

} // Tu kończy sie zasięg zmiennych x, a potem s. Ale ponieważ wartość s
  // została przeniesiona, nie dzieje się nic szczególnego.

fn bierze_na_wlasnosc(jakis_string: String) { // Zaczyna się zasięg some_string.
	println!("{}", jakis_string);
} // Tu kończy się zasięg jakis_string i wywołana zostaje funkcja `drop`.
  // Zajmowana pamięć zostaje zwolniona.

fn robi_kopie(jakas_calkowita: i32) { // Zaczyna się zasięg jakas_calkowita.
	println!("{}", jakas_calkowita);
} // Tu kończy się zasięg jakas_calkowita. Nic szczególnego się nie dzieje.

Listing 4-3: Funkcje z adnotacjami dotyczącymi własności i zasięgów

Gdybyśmy spróbowali użyć s po wywołaniu bierze_na_wlasnosc, Rust wygenerowałby błąd kompilacji. Te statyczne kontrole chronią nas przed popełnianiem błędów. Spróbuj dodać do main kod, który używa zmiennych s oraz x, żeby zobaczyć, gdzie można ich używać, a gdzie zasady systemu własności nam tego zabraniają.

Wartości zwracane i ich zasięg

Wartości zwracane mogą również przenosić własność. Listing 4-4 ilustruje przykład z podobnymi komentarzami do tych z listingu 4-3.

Plik: src/main.rs

fn main() {
    let s1 = daje_wlasnosc();       // daje_wlasnosc przenosi zwracaną
                                    // wartość do s1.

    let s2 = String::from("witaj"); // Rozpoczyna się zasięg s2.

    let s3 = bierze_i_oddaje(s2);   // s2 zostaje przeniesiona do
                                    // bierze_i_oddaje, która jednocześnie
                                    // przenosi swoją wartość zwracaną do s3.
} // Tutaj kończy się zasięg s3 i jej dane zostają zwolnione. Zasięg s2 też, ale
  // ponieważ jej dane przeniesiono, nic się nie dziejej. Zasięg s1 kończy się,
  // a jej dane zostają zwolnione.

fn daje_wlasnosc() -> String {                // daje_wlasnosc przenosi jej
                                              // wartość zwracaną do funkcji,
                                              // która ją wywołała.

    let jakis_string = String::from("wasze"); // Początek zasięgu jakis_string.

    jakis_string                              // jakis_string jest zwracany i
                                              // przeniesiony do funkcji
                                              // wywołującej.
}

// bierze_i_oddaje bierze dane w zmiennej String i zwraca je w innej.
fn bierze_i_oddaje(a_string: String) -> String { // Rozpoczyna się zasięg
                                                 // zmiennej a_string.

    a_string // a_string zostaje zwrócona i przeniesiona do funkcji wywołującej.
}

Listing 4-4: Przenoszenie własności wartości zwracanych

Własność zmiennej zachowuje się zawsze w ten sam sposób: przypisanie wartości do innej zmiennej przenosi tę wartość. Kiedy kończy się zasięg zmiennej zawierającej dane ze sterty, dane te zostaną zwolnione przez drop, chyba że przekażemy je na własność innej zmiennej.

Przyjmowanie własności, a następnie oddawanie jej przy wywołaniu każdej funkcji jest trochę pracochłonne. A co jeśli chcemy zezwolić funkcji na użycie wartości, ale nie chcemy, by przejęła ją na własność? To dość denerwujące, kiedy wszystko, co przekazujemy, musi zostać powtórnie zabrane, jeśli chcemy tego ponownie użyć. Nie mówiąc już o danych generowanych przy okazji normalnego działania funkcji, które być może także chcielibyśmy zwrócić.

Z funkcji można zwrócić kilka wartości za pomocą krotki. Listing 4-5 ilustruje ten przypadek.

Plik: src/main.rs

fn main() {
    let s1 = String::from("witaj");

    let (s2, len) = oblicz_dlugosc(s1);

    println!("Długość '{}' wynosi {}.", s2, len);
}

fn oblicz_dlugosc(s: String) -> (String, usize) {
    let dlugosc = s.len(); // len() zwraca długość łańcucha znaków.

    (s, dlugosc)
}

Listing 4-5: Zwracanie własności przez argumenty

Wymaga to dużo niepotrzebnej pracy, podczas gdy koncept ten spotykany jest powszechnie. Na szczęście dla nas, Rust wyposażony jest w referencje, które świetnie obsługują takie przypadki.

Referencje i pożyczanie

Z rozwiązaniem z krotką zastosowanym na listingu 4-5 związana jest taka niedogodność, że musieliśmy zwrócić String do funkcji wywołującej, by ta mogła dalej z niego korzystać (po wywołaniu calculate_length). Było tak dlatego że wspomniany String był przenoszony do calculate_length. Funkcję calculate_length można jednak zdefiniować tak, by jako parametr przekazywana była jedynie referencja do obiektu i dzięki temu nie był on przez calculate_length przejmowany na własność. Referencja jest podobna do wskaźnika. Jest ona adresem pod którym przechowywane są dane i dzięki niej możemy uzyskać do nich dostęp. Dane te są własnością innej zmiennej. W przeciwieństwie do wskaźnika, referencja daje gwarancję, że przez cały czas swojego życia, będzie wskazywać na poprawną wartość danego typu.

Oto jak zdefiniować i użyć funkcji calculate_length, która jako parametr otrzymuje referencję do obiektu:

Plik: src/main.rs

fn main() {
	let s1 = String::from("witaj");

	let len = calculate_length(&s1);

	println!("Długość '{}' wynosi {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
	s.len()
}

Po pierwsze proszę zauważyć, że krotki nie są nam już dalej potrzebne. Nie ma ich ani przy deklaracji zmiennej, ani w typie zwracanym przez funkcję calculate_length. Po drugie, proszę zwrócić uwagę, że przekazujemy do tej funkcji &s1 oraz, że typ jej parametru został zmieniony z String na &String. Te ampersandy oznaczają referencje (ang. references) i pozwalają na odnoszenie się (referowanie) do wartości bez przejmowania jej na własność. Jest to zilustrowane na Rysunku 4-5.

Three tables: the table for s contains only a pointer to the table
for s1. The table for s1 contains the stack data for s1 and points to the
string data on the heap.

Rysunek 4-5: &String s wskazuje na String s1

Uwaga: Przeciwieństwem referowania za pomocą & jest dereferowanie, które realizowane jest za pomocą operatora dereferencji, *. W rozdziale 8 przedstawiono przykładowe zastosowania operatora dereferencji, zaś więcej szczegółów na jego temat można znaleźć w rozdziale 15.

Przyjrzyjmy się nieco bliżej temu wywołaniu funkcji:

fn main() {
	let s1 = String::from("witaj");

	let len = calculate_length(&s1);

	println!("Długość '{}' wynosi {}.", s1, len);
}

fn calculate_length(s: &String) -> usize {
	s.len()
}

Składnia &s1 tworzy referencję, która co prawda referuje do s1, ale nie posiada go na własność. Skoro zaś go nie posiada, to wskazywana przez nią wartość nie zostanie zwolniona wraz z końcem zasięgu życia samej referencji.

Sygnatura funkcji także używa & do wskazania, że s jest referencją. Poniżej dodano kilka komentarzy z wyjaśnieniami:

fn main() {
	let s1 = String::from("witaj");

	let len = calculate_length(&s1);

	println!("Długość '{}' wynosi {}.", s1, len);
}

fn calculate_length(s: &String) -> usize { // s jest referencją do Stringa
	s.len()
} // Tu kończy się zasięg s. Ale ponieważ s nie posiada na własność tego
  // na co wskazuje, nic się nie dzieje.

Zasięg, w którym zmienna s posiada ważność, jest taki sam jak zasięg każdego innego parametru funkcji. Jednakże, ponieważ s nie posiada tego, na co wskazuje, to nie jest to kasowane gdy s wyjdzie poza swój zasięg. W przeciwieństwie do argumentów przekazywanych przez wartość, te przekazywane przez referencje nie są funkcji dawane na własność. Dlatego też funkcja nie musi więcej zwracać ich za pomocą return, by je oddać.

Przekazywanie referencji jako parametrów funkcji nazywamy pożyczaniem (ang. borrowing). I jak w prawdziwym życiu, jeśli ktoś coś posiada, możemy to od niego pożyczyć. W końcu jednak musimy mu to także oddać.

Co więc się stanie gdy spróbujemy zmodyfikować coś, co pożyczyliśmy? Wypróbujmy kod z listingu 4-6. Uwaga: on nie zadziała!

Plik: src/main.rs

fn main() {
	let s = String::from("witaj");

	change(&s);
}

fn change(some_string: &String) {
	some_string.push_str(", świecie");
}

Listing 4-6: Próba modyfikacji pożyczonej wartości

Otrzymamy następujący błąd:

$ 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

Tak jak zmienne, referencje są domyślnie niemutowalne. Nie możemy zmieniać czegoś do czego mamy referencję.

Referencje mutowalne

Możemy wyeliminować błąd z kodu z listingu 4-6 wprowadzając drobną poprawkę, by używać mutowalnej referencji (mutable reference):

Plik: src/main.rs

fn main() {
    let mut s = String::from("witaj");

    change(&mut s);
}

fn change(some_string: &mut String) {
	some_string.push_str(", świecie");
}

Po pierwsze, zmieniliśmy s by było mut. Następnie, w miejscu wywołania funkcji zmien utworzyliśmy mutowalną referencję za pomocą &mut s i ją przyjęliśmy za pomocą some_string: &mut String w sygnaturze funkcji. Taka składnia czytelnie pokazuje, że funkcja zmien będzie zmieniać wartość, którą pożycza.

Jednakże mutowalne referencję posiadają jedno spore ograniczenie: w danym zasięgu można mieć tylko jedną mutowalną referencję do konkretnych danych. Ten kod nie skompiluje się:

Plik: src/main.rs

fn main() {
    let mut s = String::from("witaj");

    let r1 = &mut s;
    let r2 = &mut s;

    println!("{}, {}", r1, r2);
}

Otrzymamy następujący błąd:

$ 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

This error says that this code is invalid because we cannot borrow s as mutable more than once at a time. The first mutable borrow is in r1 and must last until it’s used in the println!, but between the creation of that mutable reference and its usage, we tried to create another mutable reference in r2 that borrows the same data as r1.

To ograniczenie pozwala na mutowalność jedynie w bardzo kontrolowany sposób. Może ono być kłopotliwe dla początkujących rustowców, gdyż większość innych języków nie nakłada podobnych ograniczeń. Korzyścią z tego ograniczenia jest to, że Rust może zapobiec tzw. wyścigom do danych (ang. data races) i to już na etapie kompilacji. Wyścig do danych podobny jest do wyścigu (ang. race condition) i ma miejsce, gdy zachodzą następujące trzy warunki:

  • W tym samym czasie współistnieją dwa lub więcej wskaźniki umożliwiające dostęp do tych samych danych.
  • Przynajmniej jeden z tych wskaźników jest używany do zapisu danych.
  • Nie ma żadnego mechanizmu synchronizacji dostępu do danych.

Wyścigi danych powodują niezdefiniowane zachowania i mogą być trudne do zdiagnozowania, wyśledzenia w czasie wykonywania programu i naprawienia; Tymczasem Rust całkowicie im zapobiega, nie kompilując nawet kodu który je zawiera!

Oczywiście zawsze możemy użyć nawiasów klamrowych do stworzenia nowego zasięgu, pozwalając na wiele mutowalnych referencji, ale nie równocześnie:

fn main() {
    let mut s = String::from("witaj");

    {
        let r1 = &mut s;
    } // tu kończy się czas życia r1, więc odtąd możemy bez problemu utworzyć kolejną referencję

    let r2 = &mut s;
}

Podobne ograniczenie dotyczy mieszania referencji mutowalnych z niemutowalnymi. Następujący kod nie skompiluje się:

fn main() {
    let mut s = String::from("witaj");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    let r3 = &mut s; // DUŻY PROBLEM

    println!("{}, {}, i {}", r1, r2, r3);
}

Kompilator wyświetli następujący komunikat błędu:

$ 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; // DUŻY PROBLEM
  |              ^^^^^^ mutable borrow occurs here
7 |
8 |     println!("{}, {}, i {}", 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

Fiu, fiu! Mutowalnej referencji nie możemy mieć także gdy mamy niemutowalną.

Użytkownicy niemutowalnej referencji nie spodziewają się, że wartość do której ta referencja się odnosi, może się nagle zmienić! Jednakże, istnienie wielu niemutowalnych referencji niczemu nie zagraża, bo nie dają one możliwość zmiany danych i wpłynięcia na to, co odczytają inni.

Uwaga: zasięg życia referencji zaczyna się w miejscu jej utworzenia, kończy się zaś w miejscu jej ostatniego użycia. Przykładowo, następujący kod skompiluje się, bo ostatnie użycie niemutowalnej referencji, println!, występuje przed wprowadzeniem mutowalnej:

fn main() {
    let mut s = String::from("witaj");

    let r1 = &s; // no problem
    let r2 = &s; // no problem
    println!("{} and {}", r1, r2);
    // zmienne r1 i r2 dalej nie są używane

    let r3 = &mut s; // no problem
    println!("{}", r3);
}

Zasięgi życia niemutowalnych referencji r1 i r2 kończą się zaraz po println! w którym są one ostatni raz użyte, czyli przed utworzeniem mutowalnej referencji r3. Te zasięgi się nie zazębiają i dlatego kompilator ten kod akceptuje.

Błędy kompilacji związane z pożyczaniem mogą być czasami frustrujące. Pamiętajmy jednak, że nierzadko wskazują one potencjalne błędy, dokładnie wskazując problem, i to na wczesnym etapie, w czasie kompilacji, a nie wykonywania programu. Dzięki nim nie musimy odkrywać, dlaczego nasze dane są inne niż się spodziewaliśmy.

Wiszące referencje

W językach ze wskaźnikami, łatwo jest błędnie stworzyć wiszący wskaźnik, tj. taki, który odnosi się do miejsca w pamięci, które mogło być przekazane komuś innemu, poprzez zwolnienie pamięci przy jednoczesnym zachowaniu wskaźnika do niej. W Ruście natomiast, kompilator gwarantuje, że referencje nigdy nie będą wiszące: kompilator zawsze dba o to, aby jakiekolwiek dane nie wyszły poza zasięg wcześniej, niż referencje do tych danych.

Spróbujmy utworzyć wiszącą referencję. Rust nam to uniemożliwi, zgłaszając następujący błąd kompilacji:

Plik: src/main.rs

fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String {
    let s = String::from("witaj");

    &s
}

Komunikat błędu:

$ 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

This error message refers to a feature we haven’t covered yet: lifetimes. We’ll discuss lifetimes in detail in Chapter 10. But, if you disregard the parts about lifetimes, the message does contain the key to why this code is a problem:

Ten komunikat odnosi się do czegoś, czego jeszcze nie omawialiśmy: czasów życia (ang. lifetimes). Będziemy omawiać je szczegółowo w rozdziale 10. Pomijając jednak części o czasie życia, wiadomość zawiera jasne wskazanie problemu związanego z naszym kodem:

this function's return type contains a borrowed value, but there is no value
for it to be borrowed from

Przyjrzyjmy się dokładnie temu, co dzieje się na każdym etapie kodu dangle:

Plik: src/main.rs

fn main() {
    let reference_to_nothing = dangle();
}

fn dangle() -> &String { // dangle zwraca referencję do Stringa

    let s = String::from("witaj"); // s to nowy String

    &s // zwracamy referencję do Stringa s
} // Tutaj s wychodzi z zasięgu i jest zwalniane. Znika z pamięci.
  // Niebezpieczeństwo!

Jako że s jest tworzony wewnątrz dangle, to jest on zwalniany wraz z końcem dangle. Jednocześnie próbujemy zwrócić referencję do s. Ta referencja wskazywałaby na nieprawidłowy String. To niedobre! Rust nie pozwoli nam tego zrobić.

Rozwiązaniem jest zwrócenie Stringa bezpośrednio:

fn main() {
    let string = no_dangle();
}

fn no_dangle() -> String {
    let s = String::from("witaj");

    s
}

To działa bez żadnych problemów. Własność jest przenoszona na zewnątrz i nic nie jest zwalniane.

Zasady dotyczące referencji

Podsumujmy informacje na temat referencji:

  • W każdej chwili możesz mieć albo jedną referencję mutowalną albo dowolną liczbę referencji niemutowalnych.
  • Referencje zawsze muszą być poprawne.

Wkrótce przyjrzymy się innemu rodzajowi referencji: wycinkowi (ang. slice).

Wycinki

Kolejnym typem danych, który nie przejmuje własności jest wycinek (ang. slice). Wycinki pozwalają na odniesienie się do wybranej ciągłej sekwencji elementów w kolekcji, bez konieczności odnoszenia się do całej kolekcji.

Rozważmy mały problem programistyczny: napisać funkcję, która pobiera łańcuch znaków zawierający słowa rozdzielone spacjami i zwraca pierwsze słowo, które się w nim znajdzie. Jeśli funkcja nie znajdzie znaku spacji w łańcuchu, należy założyć, że cały łańcuch stanowi jedno słowo i zwrócić go w całości.

Pomyślmy nad sygnaturą tej funkcji (na razie bez użycia wycinków, by zrozumieć problem, który one rozwiązują):

fn first_word(s: &String) -> ?

Funkcja first_word przyjmuje parametr typu &String, co jest w porządku, bo funkcja ta nie potrzebuje tego łańcucha na własność. Ale jakiego typu wynik powinna zwrócić? Naprawdę brakuje nam sposobu na mówienie o części łańcucha. Możemy jednak zwrócić indeks końca słowa wskazanego przez spację. Próbujmy tego dokonać na listingu 4-7.

Plik: 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() {}

Listing 4-7: Funkcja first_word zwracająca indeks bajta w parametrze typu String

By przejść przez String element po elemencie i spróbować znaleźć spacje, konwertujemy nasz String na tablicę bajtów używając metody 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() {}

Następnie tworzymy iterator po tablicy bajtów za pomocą metody 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() {}

Iteratory omówimy szczegółowo w rozdziale 13. Na razie wiedzmy, że iter jest metodą, która daje nam każdy element w kolekcji, zaś enumerate opakowuje wynik iter i daje każdy element jako część krotki. Pierwszy element tej krotki to indeks, a drugi element to referencja do elementu z kolekcji. Użycie enumerate jest wygodniejsze od samodzielnego obliczanie indeksu.

Metoda enumerate daje krotkę, którą destrukturyzujemy za pomocą wzorca. Wzorce omówimy szczegółowo w rozdziale 6. W pętli for używamy wzorca dopasowanego do krotki, w którym i jest dopasowane do zawartego w niej indeksu, zaś &item do bajtu. Ponieważ z .iter().enumerate() otrzymujemy referencję do elementu (bajtu), we wzorcu używamy &.

Wewnątrz pętli for szukamy bajtu będącego spacją poprzez porównywanie do reprezentującego go literału. Gdy znajdziemy spację, zwracamy jej pozycję. W przeciwnym razie zwracamy długość łańcucha otrzymaną za pomocą 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() {}

Mamy teraz wprawdzie sposób na znalezienie indeksu końca pierwszego słowa, ale nie jest on wolny od wad. Zwracamy osobną liczbę typu usize, która ma jednak znaczenie jedynie w kontekście &String. Innymi słowy, ponieważ jest to wartość niezależna od naszego Stringa, to nie ma gwarancji, że w przyszłości zachowa ona ważność. Rozważmy program z listingu 4-8, który używa funkcji first_word z listingu 4-7.

Plik: 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("witaj świecie");

    let word = first_word(&s); // word otrzyma wartość 5

    s.clear(); // to czyści łańcuch s, czyniąc go równym ""

    // tutaj word wciąż ma wartość 5, ale nie ma już łańcucha
    // dla którego 5 coś znaczy. word zupełnie straciło ważność!
}

Listing 4-8: Zachowanie wyniku zwróconego przez funkcję first_word i zmiana wartości Stringa

Ten program kompiluje się bez błędów i zrobiłby to również, gdybyśmy użyli zmiennej word po wywołaniu s.clear(). Ponieważ word nie jest w ogóle związany ze stanem s, word nadal zawiera wartość 5. Moglibyśmy spróbować użyć tej wartości 5 aby wyodrębnić pierwsze słowo z s, ale byłby to błąd, ponieważ zawartość s zmieniła się od czasu gdy zapisaliśmy 5 w word.

Martwienie się o to, że indeks w word przestanie być zsynchronizowany z danymi w s jest uciążliwe i podatne na błędy! Zarządzanie tymi indeksami byłoby jeszcze bardziej uciążliwe, gdybyśmy chcieli napisać funkcję second_word (z ang. drugie słowo). Jej sygnatura musiałaby wyglądać tak:

fn second_word(s: &String) -> (usize, usize) {

Teraz śledzimy indeks początkowy i końcowy. Jest więc więcej wartości, które zostały obliczone na podstawie danych w określonym stanie, ale nie są w ogóle związane z tym stanem. Mamy trzy niepowiązane zmienne wymagające synchronizacji.

Na szczęście Rust ma rozwiązanie tego problemu: wycinki łańcuchów (ang. string slices).

Wycinki Łańcuchów

Wycinek łańcucha (ang. string slice) jest referencją do części Stringa i wygląda tak:

fn main() {
    let s = String::from("hello world");

    let hello = &s[0..5];
    let world = &s[6..11];
}

Zamiast referencji do całego Stringa, hello jest referencją do jego części, opisanej fragmentem [0..5]. Wycinek tworzymy podając zakres w nawiasach [indeks_początkowy..indeks_końcowy] i obejmuje on indeksy od indeks_początkowy włącznie do indeks_końcowy wyłącznie. Wewnętrznie, struktura danych wycinka przechowuje indeks jego początku i jego długość, która jest równa indeks_końcowy minus indeks_początkowy. Więc w przypadku let world = &s[6..11];, world jest wycinkiem składającym się ze wskaźnik do bajtu o indeksie 6 w s i z długości 5.

Rysunek 4-6 pokazuje to w formie diagramu.

Three tables: a table representing the stack data of s, which points
to the byte at index 0 in a table of the string data "hello world" on
the heap. The third table rep-resents the stack data of the slice world, which
has a length value of 5 and points to byte 6 of the heap data table.

Rysunek 4-6: Wycinek łańcucha wskazujący część Stringa

Jeżeli indeksem początkowym jest 0 to można je opcjonalnie pominąć. Innymi słowy, dwa wycinki podane poniżej są takie same:

#![allow(unused)]
fn main() {
let s = String::from("witaj");

let slice = &s[0..2];
let slice = &s[..2];
}

Analogicznie, jeśli wycinek zawiera ostatni bajt Stringa, to można zrezygnować z podania indeksu końcowego. Dwa wycinki podane poniżej także są sobie równoważne:

#![allow(unused)]
fn main() {
let s = String::from("witaj");

let len = s.len();

let slice = &s[3..len];
let slice = &s[3..];
}

Można również pominąć oba indeksy, aby uzyskać wycinek obejmujący cały łańcuch. Następujące wycinki także są sobie równoważne:

#![allow(unused)]
fn main() {
let s = String::from("witaj");

let len = s.len();

let slice = &s[0..len];
let slice = &s[..];
}

Uwaga: Indeksy zakresu wycinka łańcucha muszą znajdować się na granicach znaków UTF-8. Próba utworzenia wycinka w środku wielobajtowego znaku spowoduje zakończenie programu z błędem. We wprowadzeniu do wycinków łańcuchów zawartym w niniejszym rozdziale ograniczamy się jedynie do znaków ASCII, zaś bardziej szczegółowe omówienie obsługi UTF-8 znajduje się w sekcji "Storing UTF-8 Encoded Text with Strings"rozdziału 8.

Mając na uwadze powyższe informacje, przepiszmy first_word tak, aby zwracał wycinek. Typ oznaczający "wycinek łańcucha" zapisujemy jako &str:

Plik: 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() {}

Indeks końca słowa otrzymujemy w taki sam sposób, jak na listingu 4-7, czyli odnajdując pierwsze wystąpienie spacji. Gdy znajdziemy spację, zwracamy wycinek łańcucha używając początku łańcucha i indeksu spacji jako odpowiednio indeksu początkowego i końcowego.

Teraz, gdy wywołujemy first_word, otrzymujemy w wyniku pojedynczą wartość, związaną z danymi wejściowymi. Wartość ta składa się z referencji do punktu początkowego wycinka i liczby elementów w wycinku.

Zwrócenie wycinka zadziałałoby również w przypadku funkcji second_word:

fn second_word(s: &String) -> &str {

Mamy teraz proste API, które jest znacznie odporniejsze na błędy, ponieważ kompilator zapewni, że referencje do Stringa pozostaną ważne. Proszę przypomnieć sobie błąd w programie z listingu 4-8, kiedy uzyskaliśmy indeks do końca pierwszego słowa, ale potem wyczyściliśmy łańcuch i nasz indeks utracił ważność. Tamten kod był logicznie niepoprawny, ale jego błędy początkowo się nie ujawniały. Problemy ujawniłyby się dopiero gdybyśmy spróbowali użyć indeksu pierwszego słowa z wyczyszczonym łańcuchem. Wycinki zapobiegają podobnym błędom i dają nam znać, że mamy problem z naszym kodem znacznie wcześniej. Funkcja first_word używająca wycinków obnaża wspomniane błędy już podczas kompilacji:

Plik: 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);
}

Oto błąd kompilatora:

$ 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

Proszę sobie przypomnieć, że jedna z reguł pożyczania mówi, że jeśli mamy do czegoś niemutowalną referencję, to nie możemy równocześnie mieć do tego referencji mutowalnej. Ponieważ clear skraca Stringa, to musi przyjąć go poprzez mutowalną referencję. Makro println! używa referencji do word po wywołaniu clear, więc niemutowalna referencja musi być nadal aktywna. Rust nie pozwala, aby mutowalna referencja w clear i niemutowalna referencja w word istniały w tym samym czasie i dlatego kompilacja kończy się niepowodzeniem. Rust nie tylko uczynił nasze API łatwiejszym w użyciu, ale także sprawił, że cała klasa błędów zostanie wykryta już w czasie kompilacji!

Literały Łańcuchowe jako Wycinki

Przypomnijmy, że mówiliśmy o literałach łańcuchowych przechowywanych wewnątrz binarki. Zaś teraz, mając wiedzę o wycinkach, możemy właściwie zrozumieć literały łańcuchowe:

#![allow(unused)]
fn main() {
let s = "Witaj, świecie!";
}

Typem s jest tutaj &str: jest to wycinek wskazujący na konkretny punkt w binarce. Dlatego też literały łańcuchowe nie są modyfikowalne; &str jest referencją niemutowalną.

Wycinki Łańcuchów jako Parametry

Wiedza, że wycinki można uzyskać zarówno z literałów jak i wartości String prowadzi do jeszcze jednego ulepszenia first_word, którego można dokonać w jego sygnaturze:

fn first_word(s: &String) -> &str {

Jednak bardziej doświadczony Rustowiec dokonałby kolejnej zmiany i w zamian napisałby sygnaturę pokazaną na listingu 4-9, która może być używana zarówno z parametrem typu &String, jak i &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("witaj świecie");

    // `first_word` pracuje na wycinkach obejmujących `String`i w części lub całości
    let word = first_word(&my_string[0..6]);
    let word = first_word(&my_string[..]);
    // `first_word` pracuje też na referencjach do `String`ów, które są równoważne
    // wycinkom obejmującym całość tych `String`ów
    let word = first_word(&my_string);

    let my_string_literal = "witaj świecie";

    // `first_word` pracuje też na wycinkach literałów łańcuchowych
    let word = first_word(&my_string_literal[0..6]);
    let word = first_word(&my_string_literal[..]);

    // Ponieważ literały łańcuchowe *są* równocześnie wycinkami łańcuchów,
    // to też zadziała, i to bez składni tworzącej wycinek!
    let word = first_word(my_string_literal);
}

Listing 4-9: Ulepszenie funkcji first_word poprzez użycie wycinka łańcucha jako typu parametru s

Jeśli mamy wycinek łańcucha, to możemy go przekazać bezpośrednio. Jeśli mamy Stringa, to możemy przekazać wycinek tego Stringa lub referencję do tego Stringa. Ta elastyczność wykorzystuje deref coercions, własność, którą omówimy w sekcji "Implicit Deref Coercions with Functions and Methods" rozdziału 15.

Zdefiniowanie funkcji przyjmującej wycinek łańcucha zamiast referencji do Stringa czyni nasze API bardziej ogólnym i użytecznym bez utraty jakiejkolwiek funkcjonalności:

Plik: 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("witaj świecie");

    // `first_word` pracuje na wycinkach obejmujących `String`i w części lub całości
    let word = first_word(&my_string[0..6]);
    let word = first_word(&my_string[..]);
    // `first_word` pracuje też na referencjach do `String`ów, które są równoważne
    // wycinkom obejmującym całość tych `String`ów
    let word = first_word(&my_string);

    let my_string_literal = "witaj świecie";

    // `first_word` pracuje też na wycinkach literałów łańcuchowych
    let word = first_word(&my_string_literal[0..6]);
    let word = first_word(&my_string_literal[..]);

    // Ponieważ literały łańcuchowe *są* równocześnie wycinkami łańcuchów,
    // to też zadziała, i to bez składni tworzącej wycinek!
    let word = first_word(my_string_literal);
}

Inne Wycinki

Wycinki łańcuchów są oczywiście specyficzne dla łańcuchów. Istnieje jednak bardziej ogólny typ wycinka. Rozważmy tablicę:

#![allow(unused)]
fn main() {
let a = [1, 2, 3, 4, 5];
}

Tak samo jak możemy chcieć odwołać się do części łańcucha, możemy też chcieć odwołać się do części tablicy. Robimy to w ten sposób:

#![allow(unused)]
fn main() {
let a = [1, 2, 3, 4, 5];

let slice = &a[1..3];

assert_eq!(slice, &[2, 3]);
}

Ten wycinek ma typ &[i32]. Działa w taki sam sposób, jak wycinki łańcuchów, przechowując referencję do pierwszego elementu i długość. Używamy tego typu wycinków do wszelkiego rodzaju pozostałych kolekcji. Kolekcje te omówimy szczegółowo, gdy będziemy rozmawiać o wektorach w rozdziale 8.

Podsumowanie

Koncepcje własności, pożyczania i wycinków zapewniają bezpieczeństwo pamięci w programach Rusta w czasie kompilacji. Język Rust daje taką samą kontrolę nad wykorzystaniem pamięci jak inne języki programowania systemowego. Ale posiadanie właściciela danych automatycznie zwalniającego je gdy wychodzi poza zasięg oznacza, że nie ma potrzeby pisania i debugowania dodatkowego kodu, aby uzyskać tę kontrolę.

Własność wpływa na to, jak działa wiele innych części Rusta. Będziemy więc mówić o tych koncepcjach dalej przez resztę książki. Przejdźmy teraz do rozdziału 5, który omawia grupowanie danych w strukturach (struct).

Używanie struktur do przechowywania powiązanych danych

Struktura (ang. struct lub structure) to złożony typ danych, który pozwala spakować razem powiązane ze sobą wartości i nadać im konkretną nazwę. Jeśli znasz już jakiś obiektowy język programowania, to możesz wyobrazić sobie strukturę jako grupę atrybutów pewnego obiektu. W tym rozdziale porównamy ze sobą struktury i znane nam już krotki (ang. tuples) i pokażemy kiedy struktury są lepszym wyborem do grupowania danych.

Pokażemy też, jak definiować i używać struktur. Przedyskutujemy jak definiować powiązane z nimi funkcje opisujące zachowania związane ze strukturą, w tym metody. Struktury i typy wyliczeniowe (omówione w rozdziale 6) są cegiełkami służącymi do tworzenia nowych typów w twoim programie, dzięki którym maksymalnie wykorzystasz Rustowy mechanizm sprawdzania zgodności typów w czasie kompilacji.

Definiowanie i tworzenie instancji struktur

Struktury są podobne do krotek, które omawiane były w rozdziale 3. Podobnie do krotek, poszczególne części struktur mogą różnić się typami. W odróżnieniu od krotek, każdy fragment danych musisz nazwać, aby jasne było co każdy oznacza. W wyniku tego nazewnictwa struktury są bardziej elastyczne od krotek. Nie musisz polegać na kolejności danych, aby dostać się do wartości danej struktury.

Aby zdefiniować strukturę posługujemy się słowem kluczowym struct, po którym wstawiamy nazwę struktury. Nazwa struktury powinna odzwierciedlać znaczenie grupy danych znajdujących się w danej strukturze. Następnie, w nawiasach klamrowych definiujemy nazwy i typy fragmentów danych, które nazywamy atrybutami. Na przykład, w listingu 5-1 widzimy strukturę, w której znajdują się przykładowe dane profilu użytkownika.

Filename: src/main.rs

struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {}

Listing 5-1: User definicja struktury

Aby wykorzystać strukturę po jej zdefiniowaniu tworzymy instancję tej struktury poprzez podanie konkretnych wartości dla każdego pola. Tworzymy strukturę przez podanie jej nazwy, następnie nawiasy klamrowe zawierające pary klucz: wartość, gdzie klucze to nazwy pól, a wartości to dane, które chcemy umieścić w tych polach. Nie musimy podawać atrybutów w tej samej kolejności w jakiej zostały one zdefiniowane podczas deklaracji struktury. Innymi słowy, definicja struktury jest ogólnym szablonem, a instancje jakby wypełniają dany szablon jakimiś danymi tworząc wartości typu struktury. Przykładowa deklaracja użytkownika pokazana jest w listingu 5-2.

Filename: 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("jakisusername"),
        email: String::from("ktos@example.com"),
        sign_in_count: 1,
    };
}

Listing 5-2: Tworzenie instancji struktury User

Aby uzyskać dostęp dowybranej wartości ze struktury używamy kropki. Na przykład, jeśli chcielibyśmy zdobyć tylko adres email użytkownika moglibyśmy napisać user1.email gdziekolwiek ta wartość byłaby nam potrzebna. Jeśli instancja jest mutowalna możemy zmienić wartość używając kropki i przypisując do wybranego pola. Listing 5-3 pokazuje jak zmienić pole email w mutowalnej instancji struktury User.

Filename: 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("jakisusername"),
        email: String::from("ktos@example.com"),
        sign_in_count: 1,
    };

    user1.email = String::from("nastepnyemail@example.com");
}

Listing 5-3: Zmiana wartości pola email instancji struktury User.

Należy pamiętać, że cała instancja musi być mutowalna; Rust nie pozwala nam zaznaczyć poszczególnych pól jako mutowalnych. Jak z każdym wyrażeniem, możemy skonstruować nową instancję struktury jako ostatnie wyrażenie w ciele funkcji, aby dana instancja została zwrócona przez funkcję.

Listing 5-4 ukazuje funkcję build_user zwracającą instancję struktury User z pewnym emailem i nazwą użytkownika. Polu active przypisana jest wartość true, a polu sign_in_count przypisana jest wartość 1.

Filename: 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("ktos@example.com"),
        String::from("jakisusername123"),
    );
}

Listing 5-4: Funkcja build_user, która jako argument przyjmuje email i nazwę użytkownika, a zwraca instancję struktury User

Nadanie parametrom funkcji tej samej nazwy co polom struktury ma sens, ale przez to musimy powtarzać nazwy pól email i username, co jest trochę męczące. Jeśli jakaś struktura miałaby więcej atrybutów powtarzanie każdego z nich byłoby jeszcze bardziej męczące. Na szczęście, istnieje wygodny skrótowiec!

Skrócona inicjalizacja pól

Ponieważ nazwy parametrów i pól struktury są takie same, w listingu 5-4 możemy użyć składni tzw. skróconej inicjializacji pól (ang. field init shorthand), aby zmienić funkcję build_user, tak aby nie zmieniać jej zachowania, ale też nie powtarzając username i email. Taki zabieg widzimy w listingu 5-5.

Filename: 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("ktos@example.com"),
        String::from("jakisusername123"),
    );
}

Listing 5-5: Funkcja build_user używająca skróconej inicjalizacji pól username oraz email, które mają takie same nazwy jak parametry funkcji

Tutaj tworzymy nową instancję struktury User, która posiada pole o nazwie email. Chcemy nadać polu email wartość znajdującą się w parametrze email funkcji build_user. Skoro pole email i parametr email mają takie same nazwy wystarczy, że napiszemy email jedynie raz zamiast musieć napisać email: email.

Tworzenie instancji z innej instancji przy użyciu składni zmiany struktury

Czasem bardzo przydatnym jest stworzenie nowej struktury, która jest w zasadzie kopią innej struktury, w której chcemy zmienić tylko niektóre pola. Do tego celu zastosujemy składnię zmiany struktury.

Listing 5-6 obrazuje tworzenie instancji struktury User zapisanej do zmiennej user2 bez użycia naszej nowej składni. Nadajemy nowe wartości polom email i username, ale poza tym zostawiamy te same wartości w instancji user1, które przypisaliśmy w listingu 5-2.

Filename: src/main.rs

struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    // --snip--

    let user1 = User {
        email: String::from("ktos@example.com"),
        username: String::from("jakisusername123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        active: user1.active,
        username: user1.username,
        email: String::from("kolejny@example.com"),
        sign_in_count: user1.sign_in_count,
    };
}

Listing 5-6: Tworzenie nowej instancji struktury User używając niektórych wartości z instancji user1

Przy użyciu składni zmiany struktury możemy osiągnąć ten sam efekt mniejszym nakładem kodu, co widzimy w listingu 5-7. Składnia .. oznacza, że pozostałym polom, którym nie oznaczyliśmy ręcznie wartości przypisane zostaną wartości z danej, oznaczonej instancji.

Filename: src/main.rs

struct User {
    active: bool,
    username: String,
    email: String,
    sign_in_count: u64,
}

fn main() {
    // --snip--

    let user1 = User {
        email: String::from("ktos@example.com"),
        username: String::from("jakisusername123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("kolejny@example.com"),
        ..user1
    };
}

Listing 5-7: Użycie składni zmiany struktury w celu przypisania w User nowej wartości email, jednocześnie używając wartości pozostałych pól z user1

Kod przedstawiony w listingu 5-7 tworzy też instancję w zmiennej user2, która zmienia wartości w polach email i username, ale pozostawia wartości w polach active i sign_in_count ze zmiennej user1. The ..user1 must come last to specify that any remaining fields should get their values from the corresponding fields in user1, but we can choose to specify values for as many fields as we want in any order, regardless of the order of the fields in the struct’s definition.

Note that the struct update syntax uses = like an assignment; this is because it moves the data, just as we saw in the „Variables and Data Interacting with Move” section. In this example, we can no longer use user1 as a whole after creating user2 because the String in the username field of user1 was moved into user2. If we had given user2 new String values for both email and username, and thus only used the active and sign_in_count values from user1, then user1 would still be valid after creating user2. Both active and sign_in_count are types that implement the Copy trait, so the behavior we discussed in the „Stack-Only Data: Copy” section would apply.

Wykorzystanie braku nazywania pól w struktorach krotkowych do tworzenia nowych typów

Możesz też stworzyć struktury podobne do krotek, nazywane struktorami krotkowymi (ang. tuple structs). Atutem strukturr krotkowych jest przypisanie znaczenia polom bez ich nazywania, a jedynie przez przypisanie polom ich typu. Struktury krotkowe przydatne są najbardziej, kiedy: chciałbyś użyć krotkę, chcesz nadać jej nazwę i odróżnić ją od innych poprzez posiadanie innego typu, oraz kiedy nazywanie każdego pola (jak w normalnej strukturze) byłoby zbyt rozwlekłe lub zbędne.

Aby zdefiniować strukturę krotkową, najpierw wpisz słowo kluczowe struct, po nim nazwę struktury, a następnie typy w krotce. Dla przykładu, tutaj pokazane są działania na dwóch strukturach-krotkach, tj. Color i Point:

Filename: 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);
}

Zauważ, że black i origin mają różne typy, bo są instancjami różnych struktur krotkowych. Każda zdefiniowana struktura ma własny, niepowtarzalny typ, nawet gdy pola w dwóch strukturach mają identyczne typy. Na przykład, funkcja przyjmująca parametr typu Color nie może także przyjąć argumentu typu Point, mimo że np. oba typy mogą składać się z trzech wartości typu i32. Oprócz tego wyjątku struktury krotkowe zachowują się całkiem jak krotki: można użyć składni przypisania destrukturyzującego aby przypisać pola zmiennym, a także indeksu pola poprzedzonego ., aby uzyskać do niego dostęp.

Struktura jednostkowa bez żadnych pól

Możesz także definiować struktury nie posiadające żadnych pól! Są to tzw. struktury jednostkowe (ang. unit-like structs), bo zachowują się podobnie do (), czyli typu jednostkowego wspomnianego w rozdziale „The Tuple Type”. Struktury jednostkowe mogą być przydatne, gdy chcemy zaimplementować cechę na jakimś typie, ale nie potrzebujemy przechowywać żadnych danych. Cechy omawiamy w rozdziale 10.

Here’s an example of declaring and instantiating a unit struct named AlwaysEqual:

Filename: src/main.rs

struct AlwaysEqual;

fn main() {
    let subject = AlwaysEqual;
}

To define AlwaysEqual, we use the struct keyword, the name we want, and then a semicolon. No need for curly brackets or parentheses! Then we can get an instance of AlwaysEqual in the subject variable in a similar way: using the name we defined, without any curly brackets or parentheses. Imagine that later we’ll implement behavior for this type such that every instance of AlwaysEqual is always equal to every instance of any other type, perhaps to have a known result for testing purposes. We wouldn’t need any data to implement that behavior! You’ll see in Chapter 10 how to define traits and implement them on any type, including unit-like structs.

Własność danych struktury

W definicji struktury User w listingu 5-1 użyliśmy posiadanego typu Stringa zamiast wycinka łańcuchowego &str. To świadomy wybór, gdyż chcemy, aby instancje struktury posiadały wszystkie swoje dane oraz żeby te dane były ważne, jeśli sama struktura jest ważna.

Struktury mogą przechowywać referencje do danych należących do czegoś innego, ale do tego potrzebne byłyby informacje o długości życia zmiennych (ang. lifetime). Jest to funkcja Rusta, o której powiemy więcej w rozdziale 10. Długość życia gwarantuje nam, że dane wskazywane przez referencję są ważne dopóki struktura istnieje. Spróbujmy przechować referencję do struktury bez podania informacji o długości życia tak jak tutaj, co nie zadziała:

Nazwa pliku: src/main.rs

struct User {
    active: bool,
    username: &str,
    email: &str,
    sign_in_count: u64,
}

fn main() {
    let user1 = User {
        active: true,
        username: "jakisusername123",
        email: "ktos@example.com",
        sign_in_count: 1,
    };
}

Kompilator da ci znać, że potrzebuje specyfikatoru długości życia:

$ cargo run
   Compiling struktury v0.1.0 (file:///projects/struktury)
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` due to 2 previous errors

W rozdziale 10 pokażemy jak pozbyć się tych błędów, aby przechować referencje do innych struktur, ale póki co pozbędziemy się ich po prostu używając posiadanych typów, takich jak String zamiast referencji typu &str.

Przykładowy program wykorzystujący struktury

Aby pokazać, kiedy warto skorzystać ze struktur, napiszmy program, który policzy pole prostokąta. Zaczniemy od pojedynczych zmiennych, potem przekształcimy program tak, aby używał struktur.

Stwórzmy projekt aplikacji binarnej przy użyciu Cargo. Nazwijmy go prostokąty. Jako wejście przyjmie on szerokość i wysokość danego prostokąta i wyliczy jego pole. Listing 5-8 pokazuje krótki program obrazujący jeden ze sposobów, w jaki możemy to wykonać.

Plik: src/main.rs

fn main() {
    let width1 = 30;
    let height1 = 50;

    println!(
        "Pole prostokąta wynosi {} pikseli kwadratowych.",
        area(width1, height1)
    );
}

fn area(width: u32, height: u32) -> u32 {
    width * height
}

Listing 5-8: Obliczanie pola prostokąta o szerokości i wysokości podanych jako osobne argumenty

Uruchommy program komendą 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`
Pole prostokąta wynosi 1500 pikseli kwadratowych.

Pomimo że program z listingu 5-8 wygląda dobrze i poprawnie oblicza pole prostokąta wywołując funkcję area, do której podaje oba wymiary, to możemy napisać go czytelniej.

Problem w tym kodzie widnieje w sygnaturze funkcji area:

fn main() {
    let width1 = 30;
    let height1 = 50;

    println!(
        "Pole prostokąta wynosi {} pikseli kwadratowych.",
        area(width1, height1)
    );
}

fn area(width: u32, height: u32) -> u32 {
    width * height
}

Funkcja area ma wyliczyć pole jakiegoś prostokąta, ale przecież funkcja którą my napisaliśmy ma dwa parametry. Parametry są ze sobą powiązane, ale ta zależność nie widnieje nigdzie w naszym programie. Łatwiej byłoby ten kod zrozumieć i nim się posługiwać, jeśli szerokość i wysokość byłyby ze sobą zgrupowane. Już omówiliśmy jeden ze sposobów, w jaki można to wykonać w sekcji „Krotka” rozdziału 3, czyli poprzez wykorzystanie krotek.

Refaktoryzacja z krotkami

Listing 5-9 pokazuje jeszcze jedną wersję programu wykorzystującego krotki.

Plik: src/main.rs

fn main() {
    let rect1 = (30, 50);

    println!(
        "Pole prostokąta wynosi {} pikseli kwadratowych.",
        area(rect1)
    );
}

fn area(dimensions: (u32, u32)) -> u32 {
    dimensions.0 * dimensions.1
}

Listing 5-9: Określenie szerokości i wysokości prostokąta przy użyciu krotki

Ten program jest, w pewnych aspektach, lepszy. Krotki dodają odrobinę organizacji, oraz pozwalają nam podać funkcji tylko jeden argument. Z drugiej zaś strony ta wersja jest mniej czytelna: elementy krotki nie mają nazw, a nasze obliczenia stały się enigmatyczne, bo wymiary prostokąta reprezentowane są przez elementy krotki.

Ewentualne pomylenie wymiarów prostokąta nie ma znaczenia przy obliczaniu jego pola, ale sytuacja by się zmieniła gdybyśmy chcieli na przykład narysować go na ekranie. Musielibyśmy zapamiętać, że szerokość znajduje się w elemencie krotki o indeksie 0, a wysokość pod indeksem 1. Jeśli ktoś inny pracowałby nad tym kodem musiałby rozgryźć to samemu, a także to zapamiętać. Nie byłoby zaskakujące omyłkowe pomieszanie tych dwóch wartości, wynikające z braku zawarcia znaczenia danych w naszym kodzie.

Refaktoryzacja ze strukturami: ukazywanie znaczenia

Struktur używamy, aby przekazać znaczenie poprzez etykietowanie danych. Możemy przekształcić używaną przez nas krotkę nazywając zarówno całość jak i pojedyncze jej części, tak jak w listingu 5-10.

Plik: src/main.rs

struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!(
        "Pole prostokąta wynosi {} pikseli kwadratowych.",
        area(&rect1)
    );
}

fn area(rectangle: &Rectangle) -> u32 {
    rectangle.width * rectangle.height
}

Listing 5-10: Definicja struktury Rectangle.

Powyżej zdefiniowaliśmy strukturę i nazwaliśmy ją Rectangle. Wewnątrz nawiasów klamrowych zdefiniowaliśmy pola width i height, oba mające typ u32. Następnie w funkcji main stworzyliśmy konkretną instancję struktury Rectangle, w której szerokość wynosi 30, zaś wysokość 50.

Nasza funkcja area przyjmuje teraz jeden parametr, który nazwaliśmy rectangle, którego typ to niezmienne zapożyczenie instancji struktury Rectangle. Jak wspomnieliśmy w rozdziale 4, chcemy jedynie pożyczyć strukturę bez przenoszenia jej własności. Takim sposobem main pozostaje właścicielem i może dalej używać rect1, i dlatego używamy & w sygnaturze funkcji podczas jej wywołania.

Funkcja area dostaje się do pól width i height instancji struktury Rectangle. Proszę przy okazji zauważyć, że dostęp do pól pożyczonej instancji struktury nie powoduje przeniesienia wartości pól, dlatego często widuje się pożyczanie struktur. Teraz sygnatura funkcji area dobrze opisuje nasze zamiary: obliczenie pola danego prostokąta Rectangle poprzez wykorzystanie jego szerokości i wysokości. Bez niejasności przedstawiamy relację między szerokością a wysokością i przypisujemy logiczne nazwy wartościom zamiast indeksowania krotek wartościami 0 oraz 1. To wygrana dla przejrzystości.

Dodawanie przydatnej funkcjonalności za pomocą cech wyprowadzalnych

Miło byłoby móc wyświetlić instancję struktury Rectangle w trakcie debugowania naszego programu i zobaczyć wartość każdego pola. Listing 5-11 próbuje użyć makra println!, którego używaliśmy w poprzednich rozdziałach. To jednakowoż nie zadziała.

Plik: src/main.rs

struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!("rect1 to {}", rect1);
}

Listing 5-11: Próba wyświetlenia instancji Rectangle

Podczas próby kompilacji tego kodu wyświetlany jest błąd z poniższym komunikatem:

error[E0277]: `Rectangle` doesn't implement `std::fmt::Display`

Makro println! może formatować na wiele sposobów, a domyślnie para nawiasów klamrowych daje println! znać, że chcemy wykorzystać formatowanie Display (ang. wyświetlenie). Jest to tekst przeznaczony dla docelowego użytkownika. Widziane przez nas wcześniej prymitywne typy implementują Display automatycznie, bo przecież jest tylko jeden sposób wyświetlenia użytkownikowi symbolu 1 czy jakiegokolwiek innego prymitywnego typu. Ale kiedy w grę wchodzą struktury, sposób w jaki println! powinno formatować tekst jest mniej oczywiste, bo wyświetlać strukturę można na wiele sposobów: z przecinkami, czy bez? Chcesz wyświetlić nawiasy klamrowe? Czy każde pole powinno być wyświetlone? Przez tę wieloznaczność Rust nie zakłada z góry co jest dla nas najlepsze, więc z tego powodu struktury nie implementują automatycznie cechy Display wykorzystywanej przez println!.

Jeśli będziemy czytać dalej znajdziemy taką przydatną informację:

   = 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

Jesteśmy poinformowani, że podana przez nas struktura nie może być użyta z domyślnym formaterem i zasugerowane jest nam użycie specyfikatora formatowania :?. To tak też zróbmy! Wywołanie makra println! teraz będzie wyglądać następująco: println!("rect1 to {:?}", rect1);. Wprowadzenie specyfikatora :? wewnątrz pary nawiasów klamrowych przekazuje println!, że chcemy użyć formatu wyjścia o nazwie Debug. Cecha Debug pozwala nam wypisać strukturę w sposób użyteczny dla deweloperów, pozwalając nam na obejrzenie jej wartości podczas debugowania kodu.

Skompilujmy kod z tymi zmianami. A niech to! Nadal pojawia się komunikat o błędzie:

error[E0277]: `Rectangle` doesn't implement `Debug`

Ale kompilator ponownie daje nam pomocny komunikat:

   = help: the trait `Debug` is not implemented for `Rectangle`
   = note: add `#[derive(Debug)]` to `Rectangle` or manually `impl Debug for Rectangle`

Powyższy komunikat informuje nas, że cecha Debug nie jest zaimplementowana dla struktury Rectangle i zaleca nam dodanie adnotacji. Rust doprawdy zawiera funkcjonalność pozwalającą wyświetlić informacje pomocne w debugowaniu, ale wymaga od nas, abyśmy ręcznie i wyraźnie zaznaczyli naszą decyzję o dodaniu tej funkcjonalności do naszej struktury. W tym celu dodajemy zewnętrzny atrybut #[derive(Debug)] przed samą definicją struktury, jak w listingu 5-12.

Plik: src/main.rs

#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 30,
        height: 50,
    };

    println!("rect1 to {:?}", rect1);
}

Listing 5-12: Dodanie atrybutu nadającego cechę Debug i wyświetlanie instancji Rectangle formatowaniem przeznaczonym do celów debugowania

Teraz kiedy uruchomimy program nie wyskoczy nam żaden błąd, a naszym oczom ukaże się poniższy tekst:

$ 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 }

No nieźle! Nie jest to może najpiękniejsza reprezentacja, ale spełnia swoje zadanie i pokazuje wartości wszystkich pól tej instancji, co zdecydowanie by pomogło gdybyśmy polowali na bugi. Kiedy w grę wchodzą większe struktury miło byłoby też mieć troszkę czytelniejszy wydruk; w takich sytuacjach możemy użyć {:#?} zamiast {:?} w makrze println!. Użycie stylu {:#?} w naszym przykładzie wypisze:

$ 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,
}

Another way to print out a value using the Debug format is to use the dbg! macro, which takes ownership of an expression (as opposed to println!, which takes a reference), prints the file and line number of where that dbg! macro call occurs in your code along with the resultant value of that expression, and returns ownership of the value.

Note: Calling the dbg! macro prints to the standard error console stream (stderr), as opposed to println!, which prints to the standard output console stream (stdout). We’ll talk more about stderr and stdout in the „Writing Error Messages to Standard Error Instead of Standard Output” section in Chapter 12.

Here’s an example where we’re interested in the value that gets assigned to the width field, as well as the value of the whole 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);
}

We can put dbg! around the expression 30 * scale and, because dbg! returns ownership of the expression’s value, the width field will get the same value as if we didn’t have the dbg! call there. We don’t want dbg! to take ownership of rect1, so we use a reference to rect1 in the next call. Here’s what the output of this example looks like:

$ 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,
}

We can see the first bit of output came from src/main.rs line 10 where we’re debugging the expression 30 * scale, and its resultant value is 60 (the Debug formatting implemented for integers is to print only their value). The dbg! call on line 14 of src/main.rs outputs the value of &rect1, which is the Rectangle struct. This output uses the pretty Debug formatting of the Rectangle type. The dbg! macro can be really helpful when you’re trying to figure out what your code is doing!

Oprócz cechy Debug, Rust dostarcza cały szereg innych cech, które możemy nadać za pomocą atrybutu derive, by wzbogacić nasze typy o dodatkową funkcjonalność. Te cechy i ich zachowania opisane są w Załączniku C. Jak dodawać takim cechom własne implementacje oraz także jak tworzyć własne cechy omówimy w rozdziale 10. There are also many attributes other than derive; for more information, see the „Attributes” section of the Rust Reference.

Nasza funkcja area jest dość specyficzna: oblicza pola jedynie prostokątów. Skoro i tak nie zadziała ona z żadnym innym typem, przydatne byłoby bliższe połączenie poleceń zawartych w tej funkcji z naszą strukturą Rectangle. Kontynuacja tej refaktoryzacji zmieni funkcję area w metodę area, którą zdefiniujemy w naszym typie Rectangle.

Składnia metod

Metody są podobne do funkcji: też deklarujemy je słowem kluczowym fn, po którym umieszczamy nazwę, a czasem parametry i typ zwracanej wartości. Tak jak funkcje, zawierają jakieś polecenia wykonywane przy wywołaniu. Metody jednak różnią się od funkcji tym, że definiujemy je wewnątrz struktur (lub enumeracji czy obiektów-cech, które omówimy odpowiednio w rozdziałach 6 i 17), a ich pierwszym parametrem jest zawsze self reprezentujące instancję struktury, na której metoda jest wywołana.

Definiowanie metod

Zmieńmy funkcję area przyjmującą jako parametr instancję struktury Rectangle, w taki sposób aby od teraz area było metodą zdefiniowaną na strukturze Rectangle. To przedstawia listing 5-13.

Plik: 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!(
        "Pole prostokąta wynosi {} pikseli kwadratowych.",
        rect1.area()
    );
}

Listing 5-13: Definicja metody area w strukturze Rectangle

Aby zdefiniować funkcję w kontekście Rectangle otwieramy blok impl (czyli implementacji) dla Rectangle. Wszystko wewnątrz tego bloku będzie związane z typem Rectangle. Następnie przenosimy funkcję area do nawiasów klamrowych należących do bloku impl i jako pierwszy parametr funkcji dodajemy self w jej sygnaturze i wszędzie w jej wnętrzu. W funkcji main, zamiast jak poprzednio wywołania funkcji area, a jako argument podawania jej rect1, możemy użyć składni metody aby wywołać metodę area na instancji struktury Rectangle. Składnia metody pojawia się po nazwie instancji: dodajemy kropkę, a po niej nazwę samej metody, oraz nawiasy i argumenty jeśli są wymagane.

W sygnaturze funkcji area używamy &self zamiast rectangle: &Rectangle. The &self is actually short for self: &Self. Within an impl block, the type Self is an alias for the type that the impl block is for. Methods must have a parameter named self of type Self for their first parameter, so Rust lets you abbreviate this with only the name self in the first parameter spot. Note that we still need to use the & in front of the self shorthand to indicate that this method borrows the Self instance, just as we did in rectangle: &Rectangle. Metody mogą wejść w posiadanie self, pożyczyć self niemutowalnie, lub pożyczyć self mutowalnie, tak jakby to był jakikolwiek inny parametr.

W tym wypadku używamy &self z tego samego powodu, co &Rectangle w wersji z funkcją. Nie chcemy ani zostać właścicielem struktury, ani do niej pisać, a jedynie z niej czytać. Jeśli chcielibyśmy zmienić dane instancji w trakcie wywoływania metody użylibyśmy &mut self jako pierwszego parametru. Tworzenie metody która wchodzi w posiadanie instancji przy użyciu self jest dość rzadkie; tej techniki używamy głównie jedynie, kiedy metoda przeobraża self w coś innego i chcesz zabronić wywołującemu metody wykorzystanie oryginalnej instancji po jej transformacji.

Podstawowym celem używania metod zamiast funkcji, oprócz używania składni metody oraz braku wymogu podawania typu self w każdej sygnaturze, jest organizacja.
Umieściliśmy wszystko, co związane jest z instancją danego typu w jednym bloku impl. Dzięki temu oszczędzamy przyszłym użytkownikom kodu szukania zachowań struktury Rectangle po różnych zakątkach naszej biblioteki.

Uwaga: Możemy nadać metodzie taką samą nazwę, jak ma jedno z pól struktury. Na przykład w Rectangle możemy zdefiniować metodę width:

Plik: 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);
    }
}

Tu zdecydowaliśmy aby metoda width zwracała true jeśli wartość w polu width instancji jest większa niż 0 oraz false gdy jest równa 0: możemy użyć pola wewnątrz metody o tej samej nazwie w dowolnym celu. W main, Rust wie, że mamy na myśli metodę width, gdy bezpośrednio za rect1.width są nawiasy, oraz, że mamy na myśli pole width, gdy nawiasów nie ma.

Często, ale nie zawsze, gdy nadajemy metodzie taką samą nazwę jak polu, to chcemy aby ograniczyła ona swoje działanie jedynie do zwrócenia wartość pola. Metody takie nazywane są getterami (ang. getters). Rust, w przeciwieństwie to niektórych innych języków, nie implementuje getterów automatycznie dla pól struktury. Gettery są przydatne, ponieważ można uczynić pole prywatnym, zaś metodę publiczną, i w ten sposób umożliwić dostęp tylko do odczytu do tego pola, w publicznym API typu. Publiczne i prywatne modyfikatory dostępu do pól i metod omówimy w rozdziale 7.

Co z operatorem ->?

W C i C++ istnieją dwa różne operatory używane do wywoływania metod: symbolu . używamy do bezpośredniego wywoływania metody na obiekcie, zaś symbolu ->, jeśli metodę wywołujemy na wskaźniku do obiektu, który najpierw musimy poddać dereferencji. Innymi słowy, jeśli object jest wskaźnikiem, object->something() jest podobne do (*object).something().

Rust nie ma operatora równoważnego z ->; a za to w Ruście spotkasz funkcję automatycznej referencji i dereferencji. Wywoływanie metod jest jednym z niewielu miejsc, w których Rust wykorzystuje tę funkcję.

Działa to następująco: kiedy wywołujesz metodę kodem object.something(), Rust automatycznie dodaje &, &mut, lub * aby object pasował do sygnatury metody. Inaczej mówiąc, oba te przykłady są równoważne:

#![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);
}

Pierwszy wygląda o wiele bardziej przejrzyście. Zastosowana w niej jest automatyczna referencja, ponieważ metoda ma wyraźnie oznaczonego odbierającego (ang. receiver) - typ self. Mając informacje o odbierającym oraz o nazwie metody Rust jest w stanie jednoznacznie stwierdzić, czy metoda odczytuje (&self), zmienia (&mut self) lub konsumuje (self). Wymaganie przez Rusta oznaczenia pożyczania w odbierającym metody jest w dużej części dlaczego mechanizm posiadania jest tak ergonomiczny w używaniu.

Metody z wieloma parametrami

Poćwiczymy używanie metod implementując drugą metodę na strukturze Rectangle. Tym razem chcemy, żeby instancja struktury Rectangle przyjęła inną instancję Rectangle, i zwróciła: wartość true, jeśli ta inna instancja Rectangle całkowicie mieści się w instancji self; a jeśli nie, wartość false. Innymi słowy, zakładając, że wcześniej zdefiniowaliśmy metodę can_hold, chcemy być w stanie napisać program przedstawiony w listingu 5-14.

Plik: 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!("Czy rect2 zmieści się wewnątrz rect1? {}", rect1.can_hold(&rect2));
    println!("Czy rect3 zmieści się wewnątrz rect1? {}", rect1.can_hold(&rect3));
}

Listing 5-14: Użycie jeszcze nieistniejącej metody can_hold

Skoro wymiary rect2 są mniejsze od wymiarów rect1, a rect3 jest szerszy od rect1, spodziewamy się następującego wyniku wykonania powyższej funkcji main.

Czy rect2 zmieści się wewnątrz rect1? true
Czy rect3 zmieści się wewnątrz rect1? false

Chcemy zdefiniować metodę, więc umieścimy ją w bloku impl Rectangle. Metodę nazwiemy can_hold, i przyjmie ona jako parametr niemutowalne wypożyczenie innej instancji Rectangle. Aby dowiedzieć się jaki dokładnie typ powinien znajdować się w parametrze, spójrzmy na kod wywołujący metodę: rect1.can_hold(&rect2), przekazuje &rect2 będące niezmiennym wypożyczeniem rect2, czyli pewnej instancji Rectangle. Zależy nam jedynie na odczytaniu wartości zawartych w rect2 (do ich zmieniania wymagane byłoby mutowalne wypożyczenie), a chcemy, żeby main pozostało właścicielem rect2, abyśmy mogli ponownie wykorzystać rect2 po wywołaniu metody can_hold. Wartość zwracana przez can_hold będzie typem Boolean, a sama implementacja sprawdzi czy wysokość i szerokość instancji self są większe niż odpowiednio wysokość i szerokość innej instancji Rectangle. Dodanie nowej metody can_hold do bloku impl z listingu 5-13 pokazane jest w listingu 5-15.

Plik: 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!("Czy rect2 zmieści się wewnątrz rect1? {}", rect1.can_hold(&rect2));
    println!("Czy rect3 zmieści się wewnątrz rect1? {}", rect1.can_hold(&rect3));
}

Listing 5-15: Implementacja metody can_hold na instancji Rectangle, która przyjmuje inną instancję Rectangle jako parametr

Po uruchomieniu tego kodu funkcją main z listingu 5-14, naszym oczom ukaże się oczekiwany przez nas tekst. Metody mogą przyjmować wiele parametrów, które dodać możemy do ich sygnatur po parametrze self. Te parametry niczym nie różnią się od parametrów funkcji.

Funkcje powiązane

Wszystkie funkcje zdefiniowane w bloku impl nazywamy funkcjami powiązanymi (ang. associated functions). Można definiować funkcje powiązane, które nie mają parametru self (więc nie są metodami), bo nie potrzebują do działania instancji typu. Już mialiśmy okazję używać funkcji powiązanej. Była nią String::from zdefiniowana dla typu String.

Funkcje powiązane są często wykorzystywane do zdefiniowania konstruktorów zwracających nową instancję pewnej struktury. Zwykle nazywa sie je new, ale new nie jest specjalną nazwą wbudowaną w język. Na przykład, możemy stworzyć funkcję powiązaną square, która przyjmie tylko jeden wymiar jako parametr i przypisze go zarówno do wysokości i szerokości, umożliwiając stworzenie kwadratowego Rectangle bez podawania dwa razy tej samej wartości:

Plik: 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);
}

Słowa kluczowe Self w typie zwracanym i w ciele funkcji są aliasami do typu, który pojawia się po słowie kluczowym impl, czyli w tym przypadku do Rectangle.

Aby wywołać funkcję powiązaną używamy składni :: po nazwie struktury, np. let sq = Rectangle::square(3). Ta funkcja znajduje się w przestrzeni nazw struktury: składnia :: używana jest zarówno w kontekście funkcji powiązanych, ale i też w przestrzeniach nazw modułów. Moduły omówimy w rozdziale 7.

Wiele bloków impl

Każda struktura może mieć wiele bloków impl. Dla przykładu, kod w listingu 5-15 jest równoważny z kodem w listingu 5-16 zawierającym każdą metodę w innym bloku 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!("Czy rect2 zmieści się wewnątrz rect1? {}", rect1.can_hold(&rect2));
    println!("Czy rect3 zmieści się wewnątrz rect1? {}", rect1.can_hold(&rect3));
}

Listing 5-16: Wersja kodu z listingu 5-15 z wieloma blokami impl

W tym przypadku nie ma powodu, by metody były od siebie odseparowane w różne bloki impl, ale jest to poprawna składnia. Przypadek przydatnego wykorzystania wielu bloków impl omówimy w rozdziale 10, w którym omówimy typy uniwersalne i cechy.

Podsumowanie

Dzięki strukturom możesz tworzyć własne typy, potrzebne do rozwiązania problemów w Twojej domenie. Kiedy używasz struktury grupujesz powiązane elementy danych, a każdemu elementowi nadajesz nazwę, co sprawia, że twój kod staje się przejrzysty. W blokach impl można zdefiniować funkcje powiązane z naszym typem, których szczególnym rodzajem są metody pozwalające określić zachowanie instancji struktury.

Ale struktury to nie jest jedyny sposób na tworzenie własnych typów: poznamy kolejną funkcjonalność Rusta - enumeracje, czyli kolejne niezbędne narzędzie w twojej kolekcji.

Wyliczenia i dopasowywanie wzorców

W tym rozdziale przyjrzymy się wyliczeniom (ang. enumerations), czasem streszczanym także do samego: enum. Wyliczeniami można zdefiniować jakiś typ wymieniając wszystkie jego wartości. Najpierw zdefiniujemy i wykorzystamy wyliczenia, pokazując że mogą one przekazywać zarówno znaczenie, jak i dane. Później omówimy szczególnie przydatne wyliczenie, mianowicie Option, które deklaruje, że dana wartość może albo być obecna albo nieobecna. Po tym, zerkniemy na to, jak dopasowywanie wzorców w wyrażeniach match pozwala wybrać kod do uruchomienia dla różnych wartości wyliczeń. A na koniec, zajmiemy się wyrażeniem if let, które jest kolejnym poręcznym i zwięzłym idiomem przydatnym w pracy z wyliczeniami.

Definiowanie wyliczeń

Podczas gdy struktury pozwalają na grupowanie powiązanych pól i danych, jak Rectangle z jego szerokością i wysokością, typy wyliczeniowe pozwalają na określenie wartości jako jednej z możliwych. Na przykład, za ich pomocą możemy wyrazić, że Rectangle (prostokąt) jest jednym z możliwych kształtów, które obejmują również Circle (koło) i Triangle (trójkąt).

Weźmy na tapetę pewną sytuację, w której wyliczenia są przydatniejsze i bardziej odpowiednie niż struktury. Załóżmy, że chcemy wykonywać operacje na adresach IP. Obecnie istnieją dwa standardy adresów IP: wersja czwarta i szósta. Ponieważ to jedyne możliwe typy adresów IP na jakie napotka się nasz program, to możemy wyliczyć (ang. enumerate) wszystkie możliwe wartości, stąd nazwa wyliczeń/enumeracji.

Dany adres IP może być albo w wersji czwartej albo w szóstej, ale nigdy w obu naraz. Ta właściwość adresów IP sprawia, że wyliczenia będą dobrym wyborem, skoro mogą przyjąć tylko jedną wartość ze wszystkich swoich wariantów. Zarówno adresy wersji czwartej, jak i wersji szóstej to nadal adresy IP, więc kod zajmujący się operacjami niezależnymi od typu adresu powinien traktować oba adresy jakby były tym samym typem.

Możemy wyrazić tę myśl w kodzie definując wyliczenie IpAddrKind i wymieniając wszystkie możliwe typy adresów IP: V4 oraz V6. To są warianty tego enuma:

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 jest teraz niestandardowym typem danych dostępnym dla nas w całym kodzie.

Wartości wyliczeń

Możemy stworzyć instancje obu wariantów IpAddrKind następująco:

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) {}

Proszę zauważyć, że warianty wyliczenia dostępne są w przestrzeni jego nazwy, a więc korzystamy z dwóch dwukropków pomiędzy nazwą enuma a jego wariantem. To jest przydatne, bo teraz zarówno wartość IpAddrKind::V4, jak i IpAddrKind::V6 mają ten sam typ: IpAddrKind. A co za tym idzie, możemy napisać funkcję przyjmującą jako argument dowolny 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) {}

tę funkcję możemy wywołać z dowolnym wariantem:

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) {}

Enumeracje mają jeszcze więcej zalet. Przyjrzyjmy się naszemu typowi adresu IP dokładniej. Na chwilę obecną nie jesteśmy w stanie przechować samego adresu IP, czyli jego danych; możemy przechować jedynie jego rodzaj. Skoro dopiero co w rozdziale 5 poznaliśmy struktury, moglibyśmy pokusić się by ich użyć, tak jak pokazano na listingu 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"),
    };
}

Listing 6-1: Przechowywanie danych i wariantu IpAddrKind adresu IP przy użyciu struktury

Zdefiniowaliśmy strukturę IpAddr mającą dwa pola: kind (ang. rodzaj) typu IpAddrKind (wyliczenie zdefiniowane przez nas wcześniej) oraz address przechowującą wartość typu String. Stworzyliśmy dwie instancje tej struktury. Pierwsza, home, do pola kind ma przypisaną wartość IpAddrKind::V4, zaś do address wartość 127.0.0.1. Druga instancja, loopback ma inny wariant IpAddrKind jako wartość pola kind, ta wartość wynosi V6; oraz jako adres przypisany ma String ::1. Tym samym użyliśmy struktury aby zgrupować wartości kind i address, dzięki czemu typ adresu i sam adres są ze sobą powiązane.

Jednakże, tę samą myśl jesteśmy w stanie wyrazić zwięzłej za pomocą samego enuma: zamiast wstawiając enuma do struktury, możemy umieścić dane w każdym z wariantów enuma. Ta nowa definicja enuma IpAddr zawiera zarówno w wariancie V4 jak i V6 nową wartość o typie String:

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"));
}

Bezpośrednio dołączamy dane do każdego wariantu enuma, więc dodatkowa struktura staje się niepotrzebna. Tutaj łatwo można też dostrzec inny szczegół działania enuma: nazwa każdego jego wariantu, jest również funkcją konstruującą instancję enuma. Czyli, IpAddr::V4() jest wywołaniem funkcji, która przyjmuje argument String i zwraca instancję typu IpAddr. Ta funkcja konstruującą jest zdefiniowana automatycznie.

Wykorzystanie enuma zamiast struktury niesie ze sobą jeszcze jedną korzyść: z każdym wariantem mogą być powiązane inne typy oraz ilości danych. Adresy IP wersji czwartej zawsze będą miały cztery liczby, o wartościach pomiędzy 0 a 255. Zapisanie adresu V4 jako czterech wartości u8, a adresu V6 nadal jako typ String byłoby niemożliwe przy użyciu struktury. W przypadku wyliczeń jest to proste:

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"));
}

Pokazaliśmy kilka różnych sposobów definiowania struktur danych przechowujących adresy IP czwartej i szóstej wersji. Jak się jednak okazuje, przechowywanie adresów IP wraz z rodzajem ich wersji jest tak powszechne, że biblioteka standardowa ma gotową definicję czekającą tylko na to, aby jej użyc! Spójrzmy na definicję IpAddr w bibliotece standardowej: ma dokładnie taką samą nazwę i takie sama warianty, ale przechowuje dane o adresach za pomocą dwóch różnych struktur, zdefiniowanych osobno oraz umieszczonych w wariantach wyliczenia.

#![allow(unused)]
fn main() {
struct Ipv4Addr {
    // --snip--
}

struct Ipv6Addr {
    // --snip--
}

enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}
}

Jak demonstruje powyższy wycinek kodu, w wariantach enuma można umieścić każdy typ danych, np.: ciąg znaków (string), typ liczbowy, lub strukturę. W enumie można umieścić nawet innego enuma! Ponadto, typy w standardowej bibliotece często nie są wcale bardziej skomplikowane od wymyślonych samodzielnie.

Mimo że standardowa biblioteka definiuje własny IpAddr, nadal możemy stworzyć i używać własnej definicji bez żadnych konfliktów, bo nie zaimportowaliśmy definicji z biblioteki standardowej do zasięgu (ang. scope). Więcej informacji o importowaniu typów do zasięgu zawiera rozdział 7.

Spójrzmy na innego enuma, na przykładzie listingu 6-2: ten w swoich wariantach zawierał będzie wiele różnych typów.

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {}

Listing 6-2: Enum Message, którego warianty zawierają różne ilości i typy wartości

Ten enum definiuje cztery warianty, każdy z innymi typami:

  • Quit, nie zawiera w sobie żadnych danych.
  • Move zawiera nazwane pola, zupełnie jak struktura.
  • Write zawiera w sobie jeden String.
  • ChangeColor zawiera trzy wartości o typach i32.

Na przykładzie enuma w listingu 6-2 widzimy, że definiowanie wariantów jest podobne do definiowania kilku struktur, z taką różnicą, że nie używamy słowa kluczowego struct oraz, że wszystkie warianty zgrupowane są w typie Message. Poniższe struktury mogą zawierać te same dane co powyższe typy enuma:

struct QuitMessage; // struktura jednostkowa
struct MoveMessage {
    x: i32,
    y: i32,
}
struct WriteMessage(String); // struktura krotkowa
struct ChangeColorMessage(i32, i32, i32); // struktura krotkowa

fn main() {}

Ale jeśli użylibyśmy różnych struktur, to, w przeciwieństwie do enuma, każda z nich miałaby inny typ. Zdefiniowanie funkcji mogącej przyjąć jako parametr różne rodzaje wiadomości, nie byłoby tak proste jak przy użyciu enuma Message zdefiniowanego w listingu 6-2.

Jest jeszcze jedno podobieństwo między wyliczeniami, a strukturami: tak jak można zdefiniować metody dla struktur używając bloku impl, można je też zdefiniować dla typu wyliczeniowego. Spójrzmy na metodę o nazwie call zdefinowaną na naszym enumie Message:

fn main() {
    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
        ChangeColor(i32, i32, i32),
    }

    impl Message {
        fn call(&self) {
            // tutaj można zdefiniować ciało metody
        }
    }

    let m = Message::Write(String::from("witaj"));
    m.call();
}

Ciało metody użyje wartości self, aby uzyskać wariant enuma, na którym ta metoda została wywołana. W tym przykładzie przypisaliśmy do zmiennej m wartość Message::Write(String::from("witaj")), która, w wywołaniu m.call() stanie się parametrem self, dostępnym w ciele metody call.

Spójrzmy na kolejne wyliczenie z biblioteki standardowej, które jest bardzo przydatne i często używane, czyli Option.

Wyliczenie Option i jego przewagi nad wartościami Null

W tej sekcji znajduje się analiza typu Option, kolejnego enuma z biblioteki standardowej. Typ Option używany jest w wielu miejscach, ponieważ opisuje bardzo częsty scenariusz, w którym dana wartość może być zarówno czymś albo niczym.

Na przykład, jeśli zażądamy pierwszego elementu niepustej listy, to otrzymamy jego wartość. Jeśli zażądamy pierwszego elementu pustej listy, nie otrzymamy nic. Wyrażenie tej koncepcji za pomocą systemu typów Rusta sprawia, że kompilator jest w stanie sprawdzić, czy wzięliśmy pod uwagę wszystkie przypadki, co pozwala zapobiegać błędom (bugom) pojawiającym się bardzo często w innych językach programowania.

Przez konstrukcję języka programowania często rozumie się decyzje o zawarciu w nim jakichś funkcjonalności. Ale równie istotne jest to, jakie funkcjonalności się w nim nie znalazły. Rust nie ma wartości null znanej z wielu innych języków. Null to wartość oznaczająca brak wartości - jest to wartość pusta. W językach z pustymi wartościami, zmienne zawsze mogą być w jednym z dwóch stanów: null lub nie-null.

W swojej prezentacji z 2009 roku "Puste referencje: Błąd warty miliard dolarów" (oryg. „Null References: The Billion Dollar Mistake,”), Tony Hoare, wynalazca nulla, powiedział:

Ten błąd warty jest miliard dolarów. W tamtych czasach projektowałem pierwszy kompleksowy system typów referencji dla języków obiektowych. Moim celem było zapewnienie gwarancji, że każde użycie referencji byłoby całkowicie bezpieczne, co automatycznie sprawdzałby kompilator. Ale nie mogłem oprzeć się pokusie implementacji pustych referencji, z prostej przyczyny: było to łatwe do zaimplementowania. Ta decyzja doprowadziła do tylu niezliczonych błędów, luk i awarii systemów, że łącznie przez ostatnie czterdzieści lat pewnie spowodowała ból i szkody warte miliard dolarów.

Problem z pustymi wartościami polega na tym, że próba użycia nulla tak, jak gdyby nie był nullem, spowoduje błąd. Ponieważ ta właściwość, null lub nie-null, jest wszechobecna, niezwykle łatwo jest popełnić ten rodzaj błędu.

Jednak koncepcja, którą null próbuje wyrazić, jest przydatna: null oznacza że wartość jest obecnie nieważna lub nieobecna.

Problemem nie jest sam pomysł, ale ta konkretna implementacja pustych wartości. Rust nie ma jako takich pustych wartości null, ale istnieje w Ruście wyliczenie, które wyraża pojęcie obecności lub braku obecności danej wartości. Tym wyliczeniem jest Option<T> zdefiniowane przez bibliotekę standardową]option w następujący sposób:

#![allow(unused)]
fn main() {
enum Option<T> {
    None,
    Some(T),
}
}

Enum Option<T> jest tak przydatny, że znajduje się w prelude; nie trzeba samemu go importować. Ponadto, to samo dotyczy jego wariantów: Some i None można użyć bez prefiksu Option::. Enum Option<T> jest zwykłym wyliczeniem, a Some(T) oraz None to nadal zwykłe warianty Option<T>.

Składnia <T> jest funkcjonalnością Rusta, której jeszcze nie omówiliśmy. Jest to tzw. parametr generyczny. Bardziej szczegółowo omówimy je w rozdziale 10. Póki co, wszystko co musisz o nich wiedzieć to to, że <T> oznacza, że wariant Some enuma Option może zawierać w sobie jedną wartość dowolnego typu. Co więcej, Option<T> jest różnych typów dla różnych, konkretnych typów T. Oto niektóre przykłady używania wartości Option do przechowywania typów liczbowych oraz łańcuchowych (stringów):

fn main() {
    let some_number = Some(5);
    let some_char = Some('e');

    let absent_number: Option<i32> = None;
}

Zmienna some_number jest typu Option<i32>, zaś some_char jest typu Option<char>, który jest innym typem. Rust może wydedukować te typy, ponieważ określiliśmy wartość wewnątrz wariantu Some. W przypadku absent_number, Rust wymaga od nas adnotacji o całościowym type Option: kompilator nie może wywnioskować typu, jaki będzie posiadał wariant Some widząc tylko wartość None. Tutaj mówimy więc Rustowi, że chcemy aby absent_number było typu Option<i32>.

Widząc Some, wiemy że wartość jest obecna oraz że znajduje się ona w Some. Za to None, w pewnym sensie oznacza to samo co null, czyli brak prawidłowej wartości. To dlaczego Option<T> jest lepszy od nulla?

W skrócie, Option<T> i T (gdzie T może być dowolnym typem) są różnymi typami, więc kompilator nie pozwoli nam użyć Option<T> tak jakby była to prawidłowa wartość typu T. Na przykład, ten kod się nie skompiluje, bo próbujemy w nim dodać do siebie wartość typu i8 oraz Option<i8>:

fn main() {
    let x: i8 = 5;
    let y: Option<i8> = Some(5);

    let sum = x + y;
}

Uruchamiając ten kod, otrzymamy następujący komunikat o błędzie:

$ 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

Bezlitośnie! Ten komunikat oznacza, że Rust nie wie jak ma dodać do siebie typy i8 oraz Option<i8>, ponieważ to dwa różne typy. Kiedy w Ruście posługujemy się typem takim jak i8, kompilator zawsze gwarantuje, że jest to prawidłowa wartość. Możemy być pewni swego i kontynuować kodowanie bez sprawdzania czy dana wartość jest pusta. Jedynie kiedy posługujemy się typem Option<i8> (czy jakimkolwiek innym typem zawartym wewnątrz Option) musimy się martwić o ewentualny brak wartości, zaś kompilator upewni się, że uwzględniliśmy ten przypadek przed użyciem wartości.

Innymi słowy, musimy skonwertować wartość typu Option<T> na T zanim przyjmie ona zachowania charakterystyczne dla typu T. W większości przypadków pozwala to na pozbycie się jednego z najczęstszych problemów z nullem: zakładanie, że jakaś wartość istnieje, kiedy tak na prawdę nie istnieje.

Wyeliminowanie ryzyka nieprawidłowego założenia, że dana wartość nie jest pusta, daje nam większą pewność co do napisanego kodu. Aby dana wartość mogła nie istnieć musimy wyrazić na to zgodę definiując daną wartość jako typ Option<T>. Następnie, używając tej wartości, musimy jawnie obsłużyć przypadek, gdy wartość jest null. Wszędzie, gdzie typem wartości nie jest Option<T>, można bezpiecznie założyć, że wartość nie jest pusta. To była celowa decyzja projektowa dla Rust, aby ograniczyć wszechobecność null i zwiększyć bezpieczeństwo napisanego kodu.

Więc mając wartość typu Option<T>, jak można dostać się do wartości typu T znajdującej się w wariancie Some? Enum Option<T> ma wiele przydatnych metod odpowiednich dla różnych sytuacji; można je znaleźć w dokumentacji. Zapoznanie się z metodami typu Option<T> jest bardzo przydatne w przygodzie z Rustem.

Zwykle, aby użyć wartości typu Option<T>, musimy napisać kod sprawdzający oba warianty. Jedna część kodu będzie odpowiedzialna za wariant Some(T) i będzie ona miała dostęp do wewnętrznej wartości typu T. Druga część będzie odpowiedzialna za wariant None i ona oczywiście nie będzie miała dostępu do wartości typu T. Wyrażenie match jest konstrukcją sterującą wykonaniem, pozwalającą na tego typu zachowanie. Wyrażenie match uruchomi różny kod w zależności od tego, który wariant ma dany enum. I ten kod będzie będzie miał dostęp do danych znajdujących się w dopasowanym wariancie.

Konstrukcja Przepływu Sterowania match

Rust posiada niezwykle potężną konstrukcję przepływu sterowania match, która pozwala na porównanie wartości z serią wzorców, a następnie wykonanie kodu przypisanego do pasującego wzorca. Wzorce mogą składać się z literałów, nazw zmiennych, wieloznaczników (ang. woldcards) i wielu innych rzeczy; rozdział 18 objaśnia działanie wszystkich rodzajów wzorców. Siła match wynika z ekspresyjności wzorców i faktu, że kompilator sprawdza, czy wszystkie możliwe przypadki są obsługiwane.

Na wyrażeniu match można spojrzeć jak na maszynę do sortowania monet: monety zjeżdżają po torze wzdłuż którego znajdują się różnej wielkości otwory i każda wpada w pierwszy napotkany otwór, do którego pasuje. W ten sam sposób wartości przechodzą przez każdy wzorzec w match, aż do napotkania pierwszego wzorca, do którego wartość "pasuje". Po jego napotkaniu, wartość wpada do powiązanego z tym wzorcem bloku kodu, który zostaje wykonany.

Skoro mowa o monetach, to użyjmy ich jako przykładu z wykorzystaniem match! Możemy napisać funkcję, która pobiera nieznaną amerykańską monetę i tak jak maszyna licząca określa, jaka to moneta, oraz zwraca jej wartość w centach, jak pokazano na listingu 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() {}

Listing 6-3: Wyrażenie match dopasowujące warianty enuma do wzorców

Rozłóżmy match w funkcji value_in_cents na czynniki pierwsze. Najpierw umieszczamy słowo kluczowe match, po którym następuje wyrażenie, którym w tym przypadku jest wartość coin. To wyrażenie pełni podobną rolę do wyrażenia warunkowego używanego z if, ale jest duża różnica: w if warunek musi dawać wartość boolowską, zaś tutaj wyrażnie może być dowolnego typu. Typem coin w tym przykładzie jest enum Coin, który zdefiniowaliśmy w pierwszej linii.

Następne są odnogi match. Odnoga składa się z dwóch części: wzorca i kodu. Pierwsza odnoga ma wzorzec, którym jest wartość Coin::Penny, a następnie operator =>, który oddziela wzorzec i kod do uruchomienia. Kodem w tym przypadku jest po prostu wartość 1. Każda odnoga jest oddzielone od następnej przecinkiem.

Wykonanie wyrażenia match polega na porównaniu wartości wynikowej z wzorcem każdej z odnóg, w kolejności ich wystąpienia. Jeśli wzorzec pasuje do wartości, wykonywany jest kod związany z tym wzorcem. Jeśli wzorzec nie pasuje do wartości, wykonanie przechodzi do następnej odnogi, zupełnie jak w maszynie do sortowania monet. Możemy mieć tyle odnóg ile potrzebujemy. Na listingu 6-3, nasz match ma ich cztery.

Kod związany z każdą odnogą jest wyrażeniem, a wartość wynikowa wyrażenia w pasującej odnodze jest wartością, która zostaje zwrócona z całego wyrażenia match.

Zazwyczaj nie używamy nawiasów klamrowych, jeśli kod ramienia odnogi jest krótki, tak jak na listingu 6-3, gdzie każda odnoga jedynie zwraca wartość. Chcąc uruchomić wiele linii kodu w jednej odnodze należy użyć nawiasów klamrowych, a przecinek po odnodze jest wtedy opcjonalny. Na przykład poniższy kod drukuje „Szczęśliwy pens!“ za każdym razem, gdy metoda jest wywoływana z Coin::Penny, ale wciąż zwraca ostatnią wartość bloku, 1:

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => {
            println!("Szczęśliwy pens!");
            1
        }
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

fn main() {}

Wzorce Deklarujące Zmienne

Inną przydatną cechą odnóg match jest to, że mogą one tworzyć zmienne zainicjowane fragmentami wartości pasującej do wzorca. Tym samym pozwalają wyodrębnić wartości z wariantów enuma.

By to zilustrować, zmienimy jeden z wariantów naszego wyliczenia tak, aby przechowywał on wewnątrz dane. Od 1999 do 2008 roku Stany Zjednoczone biły ćwierćdolarówki mające po jednej ze stron różne wzory dla każdego z 50 stanów. Żadna inna moneta nie miała wzorów stanowych, więc tylko ćwiartki będą miały dodatkową wartość. Możemy ją uwzględnić w naszym typie enum poprzez zmianę wariantu Quarter tak, aby zawierał wartość typu UsState, co zrobiliśmy na listingu 6-4.

#[derive(Debug)] // byśmy mogli za chwilę zobaczyć stan
enum UsState {
    Alabama,
    Alaska,
    // --snip--
}

enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn main() {}

Listing 6-4: Enum Coin z wariantem Quarter trzymającym wartość typu UsState

Wyobraźmy sobie, że znajomy chce zebrać wszystkie 50 ćwiartek stanowych. Segregując nasze drobniaki według typów monet, będziemy podawać nazwę stanu związanego z każdą ćwiartką, by nasz przyjaciel mógł dodać ją do swojej kolekcji, gdy jeszcze takiej ćwiartki nie posiada.

W kodzie wyrażenia match dodajemy zmienną o nazwie state do wzorca dopasowującego wariant Coin::Quarter. Kiedy Coin::Quarter zostanie dopasowane, zmienna state zostanie utworzona i zainicjowana wartością wskazującą stan, z którego pochodzi ćwiartka. Następnie state może zostać użyte w kodzie tej odnogi, co pokazuje przykład:

#[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!("Ćwiartka ze stanu {:?}!", state);
            25
        }
    }
}

fn main() {
    value_in_cents(Coin::Quarter(UsState::Alaska));
}

W wywołaniu value_in_cents(Coin::Quarter(UsState::Alaska)), coin miałoby wartość Coin::Quarter(UsState::Alaska). Próby dopasowania tej wartości do kolejnych odnóg match zakończyłyby się sukcesem dopiero po dotarciu do Coin::Quarter(state). Wtedy zostałaby utworzona zmienna state o wartość UsState::Alaska. Ta zmienna zostałaby użyta w wyrażeniu println!, dając mu dostęp do wartości przechowywanej wewnątrz wariantu Quarter enuma Coin.

Dopasowywanie do Option<T>

W poprzedniej sekcji chcieliśmy wydobyć wewnętrzną wartość typu T z wariantu Some enuma Option<T>; możemy również obsłużyć Option<T> używając match, podobnie jak zrobiliśmy to z typem wyliczeniowym Coin! Zamiast porównywać monety, będziemy porównywać warianty Option<T>, ale sposób działania wyrażenia match będzie taki sam.

Powiedzmy, że chcemy napisać funkcję, która przyjmuje Option<i32> i jeśli w środku jest jakaś wartość, to dodaje do niej 1. Jeśli w środku nie ma żadnej wartości, funkcja powinna zwrócić wartość None, nie robiąc nic więcej.

Dzięki match taka funkcja jest bardzo łatwa do napisania i wygląda jak na listingu 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);
}

Listing 6-5: Funkcja używająca wyrażenia match dla Option<i32>

Przeanalizujmy bardziej szczegółowo pierwsze wykonanie plus_one. W wywołaniu plus_one(five), zmienna x ma wartość Some(5) i zostanie porównana z każdą odnogą 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);
}

Wartość Some(5) nie pasuje do wzorca None, nastąpi więc przejęcie do kolejnej odnogi:

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);
}

Czy Some(5) pasuje do Some(i)? Tak! To ten sam wariant. Zostaje zadeklarowana zmienna i, zainicjowana wartością zawartą w Some, czyli 5. Następnie wykonywany jest kod w wybranej odnodze match, który dodaje 1 do wartości i i tworzymy nową wartość Some z uzyskaną sumą 6 w środku.

Rozważmy teraz drugie wywołanie plus_one z listingu 6-5, w którym x jest None. Następuje jego porównanie do pierwszej odnogi 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);
}

Pasuje! Nie ma żadnej wartości do zwiększenia, więc program zatrzymuje się i zwraca wartość None po prawej stronie =>. Ponieważ pierwsza odnoga pasowała, to pozostałe nie są już sprawdzane.

Używanie match z typami wyliczeniowymi jest przydatne w wielu sytuacjach. Często można spotkać następujący scenariusz: enum jest dopasowywany za pomocą match, następnie z jego wewnętrznymi danymi związywana jest zmienna, która jest używana w kodzie przewidzianym dla wybranego wariantu. Początkowo może się to wydawać nieco trudne, ale po przyzwyczajeniu, okazuje się bardzo wygodne. Jest to niezmiennie ulubione narzędzie Rustowców.

Match Jest Wyczerpujący

Jest jeszcze jeden aspekt match, który musimy omówić: wzorce odnóg muszą uwzględniać wszystkie możliwości. Rozważmy następującą, błędną wersję naszej funkcji plus_one, która się nie skompiluje:

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);
}

Ten kod spowoduje błąd, bo nie uwzględnia przypadku None. Na szczęście Rust z łatwością zauważy problem. Jeśli spróbujemy skompilować ten kod, otrzymamy taki błąd:

$ 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 wie, że nie uwzględniliśmy wszystkich możliwych przypadków, a nawet wie, o którym wzorcu zapomnieliśmy! Dopasowania w Rustowym matchwyczerpujące: musimy wyczerpać wszelkie możliwości, aby kod był poprawny. Szczególnie w przypadku Option<T>, gdy Rust pilnuje byśmy jawnie obsłużyli przypadek None, chroni nas przed błędnym założeniem, że wartość zawsze jest dostępna, uniemożliwiając tym samym omawiany wcześniej błąd wart miliarda dolarów.

Wzorce Pasujące do Wszystkiego i Placeholder _

Możemy też podjąć specjalne czynności jedynie dla kilku konkretnych wartości enuma, zaś dla wszystkich pozostałych wykonać jedno domyślne działanie. Wyobraźmy sobie, że implementujemy grę, w której, jeśli wyrzucimy 3 na kostce, nasz gracz nie porusza się, ale za to dostaje nowy kapelusz. Jeśli wyrzucimy 7, nasz gracz traci kapelusz. Dla wszystkich innych wartości, nasz gracz przesuwa się po planszy o wyrzuconą liczbę oczek. Oto match, który implementuje tę logikę, z wynikiem rzutu kostką zakodowanym na sztywno zamiast wylosowanym, oraz całą pozostałą logiką reprezentowaną przez funkcje, których ciał nie podano, ponieważ ich implementacja wykracza poza zakres omawianego przykładu:

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) {}
}

Dla dwóch pierwszych odnóg wzorcami są literały 3 i 7. Dla ostatniej odnogi, która obejmuje każdą inną możliwą wartość, wzorcem jest zmienna, którą nazwaliśmy other. Kod uruchomiony dla tej odnogi przekazuje wartość other do funkcji move_player.

Ten kod kompiluje się, pomimo że nie wymieniliśmy wszystkich możliwych wartości, jakie może przyjąć u8, ponieważ ostatni wzorzec dopasuje wszystkie wartości, które nie zostały wymienione. Dzięki temu pasującemu do wszystkiego wzorcowi spełniony jest wymóg, że match musi być wyczerpujący. Proszę zauważyć, że odnoga pasująca do wszystkiego powinna być ostatnia, ponieważ wzorce są analizowane po kolei. Jeśli umieścilibyśmy ją wcześniej, dalsze odnogi nigdy by nie zostały wybrane. Dlatego Rust ostrzega, gdy dodamy odnogi po takiej, która pasuje do wszystkiego.

Rust posiada również wzorzec, którego możemy użyć, gdy chcemy dopasować wszystko, ale nie chcemy używać dopasowanej wartości: _ jest specjalnym wzorcem, który pasuje do dowolnej wartości i równocześnie nie przypisuje sobie wartością. Jego użycie mówi Rustowi, że nie zamierzamy używać wartości, więc Rust nie będzie ostrzegał o nieużywanej zmiennej.

Zmieńmy zasady gry: teraz po wyrzuceniu czegokolwiek innego niż 3 lub 7, należy rzucić ponownie. I wtedy nie ma znaczenia co wypadło, więc zmienna other nie jest dalej potrzebna i możemy ją zastąpić symbolem _:

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() {}
}

Ten przykład również spełnia wymóg wyczerpywalności, ponieważ wszystkie pozostałe wartości są w ostatniej odnodze ignorowane jawnie; nie zapomnieliśmy o niczym.

Na koniec zmienimy jeszcze raz zasady gry tak, aby wyrzucenie czegokolwiek innego niż 3 lub 7, nie miało żadnych następstw. Możemy to wyrazić używając jako kodu w odnodze _ wartości jednostkowej (czyli pustej krotki, o czym wspominaliśmy w sekcji „Krotki“):

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() {}
}

Tutaj mówimy Rustowi wprost, że nie będziemy używać żadnej wartości, która nie pasuje do wzorców poprzenich odnóg, i nie chcemy uruchamiać żadnego kodu w tym przypadku.

Więcej o wzorcach i dopasowywaniu powiemy w [rozdziale 18][ch18-00-wzorce]. Na razie jednak przejdziemy do składni if let, która może być przydatna w sytuacjach, w których wyrażenie match jest zbyt rozwlekłe.

Zwięzła Kontrola Przepływu z if let

Składnia if let łączy if i let, by obsłużyć wartości pasujące do wzorca. Składnia ta jest zwięzła, ale (bez powtarzania if let) pozwala podać tylko jeden wzorzec. Rozważmy program z listingu 6-6, który dopasowuje wartość zmiennej config_max typu Option<u8>, ale chce wykonać kod tylko jeśli ta wartość jest wariantem Some.

fn main() {
    let config_max = Some(3u8);
    match config_max {
        Some(max) => println!("Maksimum jest ustawione na {}", max),
        _ => (),
    }
}

Listing 6-6: match wykonujący kod jedynie gdy wartość jest Some

Jeśli wariantem jest Some, to wypisujemy zawartą w nim wartość przypisując ją uprzednio do zmiennej max we wzorcu. Z wariantem None nie chcemy nic robić. Aby spełnić jednak wymóg wyczerpywalności wyrażenia match, musimy dodać niewiele znaczące, szablonowe _ => () po przetworzeniu tylko jednego wariantu, co jest irytuje.

W zamian możemy napisać to samo krócej używając if let. Następujący kod zachowuje się tak samo jak match z listingu 6-6:

fn main() {
    let config_max = Some(3u8);
    if let Some(max) = config_max {
        println!("Maksimum jest ustawione na {}", max);
    }
}

Składnia if let przyjmuje wzorzec i wyrażenie oddzielone znakiem równości. Działa tak samo jak match, gdzie wyrażenie jest podane do match, a wzorzec jest jego pierwszą odnogą. W tym przypadku wzorzec to Some(max), a max zostaje zainicjowane wartością z wnętrza Some. Możemy wtedy użyć max w ciele bloku if let w taki sam sposób, w jaki użyliśmy max w odpowiedniej odnodze match. Kod w bloku if let nie jest uruchamiany, jeśli wartość nie pasuje do wzorca.

Używanie if let oznacza mniej pisania, mniej wcięć i mniej niewiele znaczącego, szablonowego kodu. Jednakże, w stosunku do match, tracimy sprawdzanie wyczerpywalności. Wybór pomiędzy match a if let zależy tego, co jest dla nas w danej sytuacji ważniejsze, uzyskanie zwięzłości czy sprawdzanie wyczerpywalności.

Innymi słowy, można myśleć o if let jako o składniowym lukrze dla match, który uruchamia kod tylko gdy wartość pasuje do podanego wzorca, równocześnie nie robiąc nic gdy nie pasuje.

Można także do if let dołączyć else. Blok kodu stojący za else pełni taką samą rolę, jak blok dla odnogi _ w wyrażeniu match równoważnym do danego if let z else. Proszę sobie przypomnieć definicję typu wyliczeniowego Coin z listingu 6-4, w którym wariant Quarter posiada wartość UsState. Za pomocą następującego wyrażenia match możemy policzyć wszystkie widziane monety niebędące ćwiartkami, jednocześnie informując o stanie, z którego pochodzą ćwiartki:

#[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!("Ćwiartka ze stanu {:?}!", state),
        _ => count += 1,
    }
}

To samo możemy też uzyskać za pomocą wyrażenia if let z else:

#[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!("Ćwiartka ze stanu {:?}!", state);
    } else {
        count += 1;
    }
}

O if let warto pamiętać w sytuacji, w której wyrażenie logiki za pomocą match jest zbyt rozwlekłe.

Podsumowanie

Pokazaliśmy, jak używać enumeracji do tworzenia typów, których zmienne mogą być jedną z zestawu wyliczonych wartości. Wskazaliśmy też, jak typ Option<T> biblioteki standardowej wykorzystuje systemu typów, aby uniknąć błędów. W zależności od tego, ile przypadków trzeba obsłużyć, można użyć match lub if let do wyodrębnienia i użycia wartości zawartych wewnątrz wariantów enuma.

Programy Rusta mogą teraz wyrażać koncepcje w danej domenie za pomocą struktur i enumów. Utworzenie niestandardowych typów i użycie ich w API zapewnia bezpieczeństwo: kompilator dba o to, aby funkcje otrzymywały tylko wartości oczekiwanego typu.

Przejdźmy teraz do omówienia modułów Rusta, które pozwalają wyrazić API, które jest dobrze zorganizowane, proste w użyciu i eksponuje tylko to, czego potrzebują użytkownicy.

Zarządzanie Rozrastającymi Się Projektami Za Pomocą Pakietów, Skrzyń i Modułów

W miarę pisania dużych programów, coraz ważniejsza staje się organizacja kodu. Dzięki pogrupowaniu powiązanych funkcjonalności i porozdzielaniu kodu, ułatwiamy odnalezienie w nim miejsc odpowiedzialnych za daną funkcjonalność, a zatem i ewentualne dokonanie zmian sposobu jej działania.

Programy, które dotychczas napisaliśmy, mieściły się w jednym module, w jednym pliku. Gdy projekt się rozrasta, warto uporządkować kod, dzieląc go na wiele modułów, a następnie wiele plików. Pakiet może zawierać wiele skrzyń binarnych i opcjonalnie jedną skrzynię biblioteczną. W miarę jak pakiet rośnie, można wyodrębnić jego części do oddzielnych skrzyń, które stają się zewnętrznymi zależnościami. Ten rozdział omawia wszystkie te techniki. Dla bardzo dużych projektów składających się z zestawu powiązanych ze sobą pakietów, które są rozwijane wspólnie, Cargo udostępnia przestrzenie robocze, które omówimy w sekcji „Przestrzenie Robocze Cargo“ rozdziału 14.

Omówimy również enkapsulację szczegółów implementacji, która pozwala na ponowne użycie kodu na wyższym poziomie: po zaimplementowaniu operacji, inny kod może wywołać nasz kod poprzez jego publiczny interfejs, bez konieczności znajomości szczegółów implementacji. Sposób, w jaki piszemy kod określa, które części są publiczne do wykorzystania przez inny kod, a które są prywatnymi szczegółami implementacji i, w związku z tym, zastrzegamy sobie prawo do ich swobodnej zmiany. Wszystko to jest kolejnym sposobem na ograniczenie liczby szczegółów, które musimy mieć w głowie.

Powiązanym pojęciem jest zasięg: osadzony kontekst, w którym pisany jest kod i który zawiera zestaw nazw, o których mówimy, że są „w zasięgu“. Czytając, pisząc i kompilując kod, programiści i kompilatory muszą wiedzieć, czy dana nazwa w danym miejscu odnosi się do zmiennej, funkcji, struktury, enumeracji, modułu, stałej lub innego elementu i co ten element oznacza. Można tworzyć zasięgi i decydować, które nazwy są w zasięgu a które poza nim. Nie można mieć jednak dwóch elementów o tej samej nazwie w tym samym zasięgu; ale dostępne są narzędzia do rozwiązywania konfliktów nazw.

Rust posiada szereg rozwiązań, które pozwalają zarządzać organizacją kodu. W szczególności pozwalają one decydować które szczegóły są eksponowane, które są prywatne, oraz jakie nazwy znajdują się w poszczególnych zasięgach. Te rozwiązania czasami nazywane są zbiorczo systemem modułów i obejmują:

  • Pakiety (ang. packages): Funkcjonalność Cargo umożliwiająca budowanie, testowanie i udostępnianie skrzyń
  • Skrzynie (ang. crates): Drzewo modułów tworzących bibliotekę lub plik wykonywalny
  • Moduły (ang. modules) i użycia (ang. use): Pozwala kontrolować organizację, zasięg i prywatność ścieżek
  • Ścieżki (ang. paths): Sposób nazywania elementu, takiego jak struktura, funkcja lub moduł

W tym rozdziale omówimy wszystkie te rozwiązania i interakcje między nimi. Wyjaśnimy też jak używać ich do zarządzania zasięgiem. Na koniec powinieneś dogłębnie zrozumieć system modułów i być w stanie pracować z zasięgami jak zawodowiec!

Pakiety i Skrzynie

Pierwszymi elementami systemu modułów, które omówimy są pakiety i skrzynie.

Skrzynka (ang. crate) jest najmniejszą jednostką kodu braną jednorazowo pod uwagę przez kompilator Rusta. Nawet jeżeli uruchomimy rustc zamiast cargo i podamy pojedynczy plik z kodem źródłowym (tak jak zrobiliśmy to w sekcji „Pisanie i uruchamianie programu w Rust“ rozdziału 1), kompilator potraktuje ten plik jako skrzynię. Skrzynie mogą zawierać moduły, a moduły mogą być zdefiniowane w innych plikach, które są kompilowane razem ze skrzynią, co zostanie pokazane dalej.

Skrzynia może przybrać jedną z dwóch form: skrzyni binarnej lub skrzyni bibliotecznej. Skrzynie binarne (ang. binary crate) to programy, które można skompilować do postaci wykonywalnej, możliwej do uruchomienia. Może to być np. program linii poleceń lub serwer. Każda skrzynia binarna musi posiadać funkcję o nazwie main, która definiuje, co się stanie, gdy program zostanie uruchomiony. Wszystkie skrzynie, które stworzyliśmy do tej pory były skrzyniami binarnymi.

Skrzynie biblioteczne (ang. library crate) nie mają funkcji main i nie kompilują się do pliku wykonywalnego. Zamiast tego definiują funkcjonalność przewidzianą do współdzielenia przez wiele projektów. Na przykład skrzynia rand, której używaliśmy w rozdziale 2, zapewnia funkcjonalność generującą liczby losowe. Gdy Rustowcy mówią po prostu „skrzynia“, zazwyczaj mają na myśli właśnie skrzynię biblioteczną i używają „skrzyni“ zamiennie z ogólnym, programistycznym pojęciem „biblioteki“.

Korzeń skrzyni (ang. crate root) jest plikiem źródłowym, od którego kompilator Rust rozpoczyna i który stanowi główny moduł skrzyni (moduły wyjaśnimy dogłębnie w sekcji „Defining Modules to Control Scope and Privacy“).

Pakiet (ang. package) jest zapewniającym pewną funkcjonalność zestawem jednej lub więcej skrzyń. Pakiet zawiera plik Cargo.toml, który opisuje jak te skrzynie zbudować. Cargo w rzeczywistości jest pakietem, który zawiera binarną skrzynię z narzędziem wiersza poleceń, służącym do budowania kodu. Pakiet Cargo zawiera również skrzynię biblioteczną, od której zależy skrzynia binarna. Inne projekty mogą zależeć od skrzyni bibliotecznej Cargo, aby używać tej samej logiki, której używa narzędzie wiersza poleceń Cargo.

Pakiet może zawierać dowolną liczbę skrzyń binarnych i co najwyżej jedną skrzynię biblioteczną. Pakiet musi zawierać przynajmniej jedną skrzynię, niezależnie od tego czy jest to skrzynia biblioteczna czy binarna.

Prześledźmy, co się dzieje, gdy tworzymy pakiet. Najpierw wpisujemy polecenie cargo new:

$ cargo new my-project
     Created binary (application) `my-project` package
$ ls my-project
Cargo.toml
src
$ ls my-project/src
main.rs

Po uruchomieniu cargo new, użyliśmy ls aby zobaczyć co Cargo utworzyło. W katalogu projektu znajduje się plik Cargo.toml konstytuujący pakiet. Jest też katalog src, który zawiera main.rs. Po otworzeniu Cargo.toml w edytorze tekstu, można zauważyć, że nie ma tam wzmianki o src/main.rs. Cargo stosuje konwencję, zgodnie z którą src/main.rs jest korzeniem skrzyni binarnej o tej samej nazwie co pakiet. Podobnie, Cargo wie, że jeśli katalog pakietu zawiera src/lib.rs, to pakiet zawiera bibliotekę o tej samej nazwie co pakiet, a src/lib.rs jest korzeniem jej skrzyni. Cargo przekazuje pliki skrzyni do rustc, aby zbudować bibliotekę lub program.

Tutaj mamy pakiet, który zawiera tylko src/main.rs, co oznacza, że zawiera tylko skrzynię binarną o nazwie my-project. Jeśli pakiet zawiera src/main.rs i src/lib.rs, to ma dwie skrzynie: binarną i biblioteczną, obie o tej samej nazwie co pakiet. Pakiet może mieć wiele skrzyń binarnych poprzez umieszczenie plików w katalogu src/bin: każdy plik będzie oddzielną skrzynią binarną.

Definiowanie Modułów by Kontrolować Zasięg i Prywatności

W tym rozdziale porozmawiamy o modułach i innych częściach systemu modułów, mianowicie o ścieżkach, które pozwalają na nazywanie elementów; słowie kluczowym use, które włącza ścieżkę w zasięg; oraz słowie kluczowym pub, które upublicznia elementy. Omówimy również słowo kluczowe as, pakiety zewnętrzne i operator glob.

Zaczniemy od podania listy reguł, będącej swoistą ściągą, przydatną podczas organizowania własnego kodu. Następnie szczegółowo wyjaśnimy poszczególne reguły.

Ściąga z Modułów

Przedstawiamy tutaj krótkie kompendium omawiające jak moduły, ścieżki, słowo kluczowe use i słowo kluczowe pub działają w kompilatorze i jak większość programistów organizuje swój kod. Jest to świetne miejsce, do którego można sięgnąć, aby przypomnieć sobie, jak działają moduły. Zaś przykłady każdej z podanych reguł będziemy omawiać w dalszej części rozdziału.

  • Start z korzenia skrzyni: Podczas kompilowania skrzyni, kompilator najpierw zagląda do pliku głównego skrzyni (zazwyczaj src/lib.rs dla skrzyni bibliotecznej lub src/main.rs dla skrzyni binarnej) w poszukiwaniu kodu do skompilowania.
  • Deklarowanie modułów: W pliku głównym skrzyni, można deklarować nowe moduły; powiedzmy, że zadeklarujemy moduł „garden“ (z ang. ogród) za pomocą mod garden;. Kompilator będzie szukał kodu tego modułu w następujących miejscach:
    • Zaraz za mod garden, w nawiasach klamrowych, które zastępują średnik po mod garden
    • W pliku src/garden.rs
    • W pliku src/garden/mod.rs
  • Deklarowanie podmodułów: W każdym pliku innym niż główny plik skrzyni, można zadeklarować podmoduły. Na przykład, można zadeklarować mod vegetables; (z ang. warzywa) w src/garden.rs. Kompilator będzie szukał kodu podmodułu w katalogu o nazwie zgodnej z modułem nadrzędnym, w następujących miejscach:
    • Zaraz za mod vegetables, w nawiasach klamrowych, które zastępują średnik po mod vegetables
    • W pliku src/garden/vegetables.rs
    • W pliku src/garden/vegetables/mod.rs
  • Ścieżki do kodu w modułach: Gdy moduł jest częścią skrzyni, można odwołać się do kodu w tym module z dowolnego innego miejsca tej skrzyni, gdy tylko pozwalają na to zasady prywatności, używając ścieżki do kodu. Na przykład, do typu Asparagus (z ang. szparag) w podmodule vegetables modułu garden można odwołać się za pomocą crate::garden::vegetables::Asparagus.
  • Prywatne a publiczne: Kod zawarty w module domyślnie jest prywatny i niedostępny dla modułów nadrzędnych. Aby upublicznić moduł, trzeba go zadeklarować za pomocą pub mod zamiast mod. By upublicznić zawarte w module elementy, należy umieścić pub przed ich deklaracjami.
  • Słowo kluczowe use: Słowo kluczowe use tworzy skróty do elementów, ograniczając tym samym powtarzanie długich ścieżek. W dowolnym zasięgu, w którym typ crate::garden::vegetables::Asparagus jest dostępny, można z pomocą use crate::garden::vegetables::Asparagus; utworzyć do niego skrót i, od tego momentu, pisać Asparagus, aby ten typ wykorzystać.

Powyższe zasady zilustrujemy na przykładzie skrzyni binarnej o nazwie backyard (z ang. podwórko). Katalog tej skrzyni, również nazwany backyard, zawiera następujące pliki i katalogi:

backyard
├── Cargo.lock
├── Cargo.toml
└── src
    ├── garden
    │   └── vegetables.rs
    ├── garden.rs
    └── main.rs

Plikiem głównym tej skrzyni jest src/main.rs o następującej zawartości:

Plik: src/main.rs

use crate::garden::vegetables::Asparagus;

pub mod garden;

fn main() {
    let plant = Asparagus {};
    println!("I'm growing {:?}!", plant);
}

Linia pub mod garden; mówi kompilatorowi, aby uwzględnił kod, który znajduje się w src/garden.rs, czyli:

Filename: src/garden.rs

pub mod vegetables;

Tutaj, pub mod vegetables; oznacza uwzględnienie także kodu z src/garden/vegetables.rs. Oto ten kod:

#[derive(Debug)]
pub struct Asparagus {}

Teraz dogłębniej omówmy powyższe reguły i zademonstrujmy je w działaniu!

Grupowanie Spokrewnionego Kodu w Modułach

Moduły pozwalają nam tak zorganizować kod w obrębie skrzyni, by był czytelny i łatwy do wielokrotnego wykorzystania. Moduły pozwalają nam również kontrolować prywatność elementów, ponieważ kod wewnątrz modułu jest domyślnie prywatny. Elementy prywatne stanowią wewnętrzne szczegóły implementacji, niedostępne z zewnątrz. Możemy zdecydować się na upublicznienie modułów i zawartych w nich elementów, aby zewnętrzny kod mógł je wykorzystywać i być od nich zależny.

Jako przykład napiszmy skrzynię biblioteczną, dostarczającą funkcjonalność restauracji. Zdefiniujemy sygnatury funkcji, ale pozostawimy ich ciała puste, aby skupić się na organizacji kodu, a nie na implementacji restauracji.

W branży restauracyjnej niektóre części restauracji określane są jako front of house, a inne jako back of house. Front of house to obszar, w którym przebywają klienci; w nim gospodarze sadzają gości, kelnerzy przyjmują zamówienia i płatności, a barmani przygotowują drinki. Back of house to miejsca, w których pracują kucharze przygotowujący posiłki, zmywacze myjący naczynia, oraz kierownicy wykonujący prace administracyjne.

Aby zorganizować naszą skrzynię zgodnie z powyższym podziałem, uporządkujemy jej funkcjonalności w zagnieżdżonych modułach. Utworzymy nową bibliotekę o nazwie restaurant, uruchamiając cargo new restaurant --lib; następnie wpiszemy kod z listingu 7-1 do src/lib.rs, aby zdefiniować niektóre moduły i sygnatury funkcji. Oto sekcja frontowa:

Plik: 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() {}
    }
}

Listing 7-1: Moduł front_of_house zawierający inne moduły, które zawierają funkcje

Moduł definiujemy za pomocą słowa kluczowego mod, po którym następuje nazwa modułu (w tym przypadku front_of_house). Następnie umieszczamy ciało modułu w nawiasach klamrowych. Wewnątrz modułów możemy umieszczać inne moduły, co w tym przypadku uczyniliśmy z modułami hosting i serving. Moduły mogą również zawierać definicje innych elementów, takich jak strukty, enumy, stałe, cechy i—jak na listingu 7-1—funkcje.

Moduły pozwalają na pogrupowanie powiązanych ze sobą definicji i nazwanie relacji pomiędzy nimi. Dzięki pogrupowaniu, programiści mogą łatwiej poruszać się po kodzie i nie muszą czytać wszystkiego by odnaleźć interesujące ich definicje. Zaś dodając nową funkcjonalność wiedzą, gdzie umieścić kod.

Wcześniej wspomnieliśmy, że src/main.rs i src/lib.rs nazywane są korzeniami skrzyni. Przyczyną nadania im takiej nazwy jest fakt, że zawartość każdego z tych plików konstytuuje moduł o nazwie crate, będący korzeniem struktury złożonej z modułów skrzyni, zwanej drzewem modułów.

Listing 7-2 pokazuje drzewo modułów dla struktury z listingu 7-1.

crate
 └── front_of_house
     ├── hosting
     │   ├── add_to_waitlist
     │   └── seat_at_table
     └── serving
         ├── take_order
         ├── serve_order
         └── take_payment

Listing 7-2: Drzewo modułów dla kodu pokazanego na listingu 7-1

Drzewo to pokazuje w jaki sposób moduły zagnieżdżone są w innych; na przykład, hosting jest zagnieżdżony w front_of_house. Drzewo ukazuje również, że niektóre moduły są równorzędne, co oznacza, że są zdefiniowane w tym samym module; hosting i serving są równorzędne, bo oba są zdefiniowanym w front_of_house. Jeśli moduł A jest zawarty wewnątrz modułu B, mówimy, że moduł A jest podrzędny w stosunku do modułu B oraz, że moduł B jest nadrzędny w stosunku do modułu A. Proszę zauważyć, że korzeniem drzewa modułów jest zdefiniowany domyślnie i niejawnie moduł o nazwie crate.

Drzewo modułów przypomina drzewo katalogów w systemie plików na komputerze. Podobnie do katalogów w systemie plików, moduły służą organizacji (w ich przypadku, chodzi o organizację kodu). I analogicznie do plików w katalogach, potrzebujemy sposobu na odnajdywanie naszych modułów.

Ścieżki Do Elementów W Drzewie Modułów

Podobnie jak podczas nawigowania po systemie plików, elementy w drzewie modułów wskazujemy za pomocą ścieżek. Aby wywołać funkcję, musimy znać do niej ścieżkę.

Każda ścieżka jest jednego z następujących dwóch rodzajów:

  • Ścieżka bezwzględna jest pełną ścieżką startującą od korzenia skrzyni; dla kodu z zewnętrznej skrzyni, notacja ścieżki bezwzględnej zaczyna się od nazwy skrzyni, a dla kodu z bieżącej skrzyni, od słowa crate.
  • Ścieżka względna startuje z bieżącego modułu i jej zapis zaczyna się od self, super, lub identyfikatora w bieżącym module.

Zarówno ścieżki bezwzględne jak i względne notujemy za pomocą jednego lub więcej identyfikatorów oddzielonych podwójnymi dwukropkami (::).

Powróćmy do listingu 7-1 i załóżmy, że chcemy wywołać funkcję add_to_waitlist. By to uczynić, musimy wpierw odpowiedzieć na pytanie: jaka jest ścieżka do funkcji add_to_waitlist? Listing 7-3 obejmuje skrót listingu 7-1, pozbawiony niektórych modułów i funkcji.

Prezentujemy dwa sposoby wywołania funkcji add_to_waitlist z nowej funkcji eat_at_restaurant zdefiniowanej w korzeniu skrzyni. Pomimo że ścieżki podane w przykładzie są poprawne, to jego skompilowanie nie jest możliwe, ze względu na inny problem. Za chwilę wyjaśnimy jaki.

Funkcja eat_at_restaurant jest częścią publicznego API naszej skrzyni bibliotecznej, więc oznaczyliśmy ją słowem kluczowym pub. Bardziej szczegółowo omawiamy to słowo w sekcji "Exposing Paths with the pub Keyword".

Plik: src/lib.rs

mod front_of_house {
    mod hosting {
        fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Ścieżka bezwzględna
    crate::front_of_house::hosting::add_to_waitlist();

    // Ścieżka względna
    front_of_house::hosting::add_to_waitlist();
}

Listing 7-3: Wywołanie funkcji add_to_waitlist przy wykorzystaniu bezwzględnej oraz względnej ścieżki

W pierwszym wywołaniu funkcji add_to_waitlist w eat_at_restaurant, używamy ścieżki bezwzględnej. Ponieważ funkcja add_to_waitlist jest zdefiniowana w tej samej skrzyni co eat_at_restaurant, to zapis tej ścieżki zaczynamy słowem crate. Po tym słowie wymieniamy kolejne moduły, aż dotrzemy do add_to_waitlist. Można sobie wyobrazić system plików o takiej samej strukturze: aby uruchomić program add_to_waitlist, podalibyśmy ścieżkę /front_of_house/hosting/add_to_waitlist; użycie nazwy crate by zacząć od korzenia skrzyni jest jak użycie / by zacząć od korzenia systemu plików.

W drugim wywołaniu funkcji add_to_waitlist w eat_at_restaurant, używamy ścieżki względnej. Ścieżka ta zaczyna się od front_of_house, czyli nazwy modułu zdefiniowanego na tym samym poziomie drzewa modułów co eat_at_restaurant. Jej odpowiednikiem w systemie plików byłoba ścieżka front_of_house/hosting/add_to_waitlist. Rozpoczęcie od nazwy modułu oznacza, że ścieżka jest względna.

Decyzja czy użyć ścieżki względnej czy bezwzględnej zależy od projektu. Od tego, czy bardziej prawdopodobne jest przeniesienie kodu definiującego element osobno czy razem z kodem, który go używa. Na przykład, jeśli przeniesiemy moduł front_of_house i funkcję eat_at_restaurant do modułu o nazwie customer_experience, będziemy musieli zaktualizować bezwzględną ścieżkę do add_to_waitlist, ale ścieżka względna nadal będzie poprawna. Jeśli jednak przeniesiemy samą funkcję eat_at_restaurant do modułu o nazwie dining, bezwzględna ścieżka do wywołania add_to_waitlist pozostanie taka sama, zaś względna ścieżka będzie wymagała uaktualnienia. Ogólnie powinniśmy preferować podawanie ścieżek bezwzględnych, ponieważ jest bardziej prawdopodobne, że będziemy chcieli przenieść definicje kodu i wywołania elementów niezależnie od siebie.

Spróbujmy skompilować listing 7-3 i dowiedzmy się, dlaczego nie jest to jeszcze możliwe. Otrzymany błąd jest pokazany na listingu 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

Listing 7-4: Błędy kompilatora otrzymane podczas próby zbudowania kodu z listing 7-3

Komunikaty błędów mówią, że moduł hosting jest prywatny. Innymi słowy, mamy poprawne ścieżki do modułu hosting i funkcji add_to_waitlist, ale Rust nie pozwoli nam ich użyć, ponieważ nie ma dostępu do prywatnych sekcji. W Ruście wszystkie elementy (funkcje, metody, strukty, enumy, moduły i stałe) są domyślnie prywatne, niedostępne dla modułów nadrzędnych. Dlatego by uczynić element taki jak funkcja lub struktura prywatnym, wystarczy umieścić go w module.

Elementy w module nadrzędnym nie mogą używać prywatnych elementów wewnątrz modułów podrzędnych, ale elementy w modułach podrzędnych mogą używać elementów w swoich modułach nadrzędnych. Dzieje się tak dlatego, że moduły podrzędne opakowują i ukrywają swoje szczegóły implementacji, ale moduły podrzędne widzą kontekst, w którym są zdefiniowane. Kontynuując naszą metaforę, pomyślmy o zasadach prywatności jak o zapleczu restauracji: to, co się tam dzieje, jest prywatne, niedostępne dla klientów restauracji. Ale menedżerowie biura mogą zobaczyć i zrobić wszystko w restauracji, którą prowadzą.

System modułów w Ruście ukrywa domyślnie wewnętrzne szczegóły implementacji. Dzięki temu wiadomo, które części wewnętrznego kodu można bezpiecznie zmienić, nie psując przy tym kodu zewnętrznego. Równocześnie, za pomocą słowa kluczowego pub można upublicznić element, tym samym udostępniając nadrzędnym modułom część wewnętrznego kodu z modułu podrzędnego.

Eksponowanie Ścieżek Za Pomocą Słowa Kluczowego pub.

Wróćmy do błędu z listingu 7-4, który mówił, że moduł hosting jest prywatny. Chcemy, aby funkcja eat_at_restaurant w module nadrzędnym miała dostęp do funkcji add_to_waitlist w module podrzędnym. Dlatego oznaczamy moduł hosting słowem kluczowym pub, co pokazano na listingu 7-5.

Plik: src/lib.rs

mod front_of_house {
    pub mod hosting {
        fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Ścieżka bezwzględna
    crate::front_of_house::hosting::add_to_waitlist();

    // Ścieżka względna
    front_of_house::hosting::add_to_waitlist();
}

Listing 7-5: Deklarowanie modułu hosting jako pub by użyć go z eat_at_restaurant

Niestety, próba skompilowania kodu z listingu 7-5 nadal kończy się błędem, co pokazano na listingu 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

Listing 7-6: Błędy kompilatora przy budowaniu kodu z listing 7-5

Co się stało? Dodanie słowa kluczowego pub przed mod hosting upublicznia moduł. Dzięki tej zmianie, jeśli mamy dostęp do front_of_house, to mamy też dostęp do hosting. Ale zawartość hosting nadal jest prywatna; upublicznienie modułu nie upublicznia jego zawartości. Słowo kluczowe pub dla modułu pozwala jedynie na odwołanie się do niego przez kod w modułach nadrzędnych, a nie na dostęp do jego wewnętrznego kodu. Ponieważ moduły są kontenerami, nie wystarczy upublicznić jedynie modułu; należy pójść dalej i zdecydować się na upublicznienie jednego lub więcej elementów z jego wnętrza.

Błędy na listingu 7-6 mówią, że funkcja add_to_waitlist jest prywatna. Tak samo jak modułów, zasady prywatności dotyczą również struktur, typów wyliczeniowych, funkcji i metod.

Upublicznijmy również funkcję add_to_waitlist, dodając przed jej definicją słowo kluczowe pub, jak na listingu 7-7.

Filename: src/lib.rs

mod front_of_house {
    pub mod hosting {
        pub fn add_to_waitlist() {}
    }
}

pub fn eat_at_restaurant() {
    // Ścieżka bezwzględna
    crate::front_of_house::hosting::add_to_waitlist();

    // Ścieżka względna
    front_of_house::hosting::add_to_waitlist();
}

Listing 7-7: Dodanie słowa kluczowego pub do mod hosting i fn add_to_waitlist pozwala nam wywołać tę funkcję z eat_at_restaurant

Teraz kod się kompiluje! Aby zobaczyć dlaczego dodanie słowa kluczowego pub spowodowało, że można użyć ścieżek zawartych w eat_at_restaurant z poszanowaniem reguł prywatności, przeanalizujmy ścieżki bezwzględne i względne.

Nasza ścieżka bezwzględna zaczyna się od crate, czyli korzenia drzewa modułów naszej skrzyni. Moduł front_of_house jest zdefiniowany w korzeniu skrzyni. Mimo że front_of_house nie jest publiczny, to ponieważ funkcja eat_at_restaurant jest zdefiniowana w tym samym module co front_of_house (czyli eat_at_restaurant i front_of_house są równorzędne), możemy odwoływać się do front_of_house z eat_at_restaurant. Następny jest moduł hosting oznaczony symbolem pub. A ponieważ możemy uzyskać dostęp do modułu nadrzędnego w stosunku do hosting, to możemy też uzyskać dostęp do hosting. Ostatecznie, ponieważ funkcja add_to_waitlist jest oznaczona jako pub i możemy uzyskać dostęp do jej modułu nadrzędnego, to mamy prawo ją wywołać!

W przypadku ścieżki względnej, logika jest taka sama jak w przypadku ścieżki bezwzględnej, z wyjątkiem pierwszego kroku: zamiast zaczynać od korzenia skrzyni, ścieżka zaczyna się od front_of_house. Rozpoczęcie ścieżki względnej od modułu, w którym zdefiniowany jest eat_at_restaurant (a tak jest w przypadku front_of_house) oczywiście zadziała. Następnie, ponieważ hosting i add_to_waitlist są oznaczone jako pub, to reszta ścieżki również zadziała, tak jak i samo wywołanie funkcji!

Jeśli planujesz udostępnić swoją skrzynię biblioteczną, aby inne projekty mogły korzystać z twojego kodu, twoje publiczne API jest umową z użytkownikami skrzyni, która określa, w jaki sposób mogą oni korzystać z twojego kodu. Jest wiele aspektów dotyczących zarządzania zmianami w publicznym API tak, by ułatwić utrzymanie od niego zależności. Rozważania na ich temat wykraczają jednak poza zakres tej książki; zainteresowanych tym tematem odsyłamy do The Rust API Guidelines.

Pakiety z Programami i Bibliotekami - Najlepsze Praktyki

Wspomnieliśmy, że pakiet może równocześnie zawierać zarówno korzeń skrzyni binarnej src/main.rs jak i korzeń skrzyni bibliotecznej src/lib.rs, i obie skrzynie będą miały domyślnie nazwę pakietu. Zazwyczaj takie pakiety w skrzyni binarnej będą miały jedynie kod niezbędny do uruchomienia programu wykonywalnego i wywołania kodu ze skrzyni bibliotecznej. Dzięki temu inne projekty będą mogły wykorzystać prawie całą funkcjonalność zapewnianą przez pakiet, ponieważ kod skrzyni bibliotecznej może być współdzielony.

Drzewo modułów powinno być zdefiniowane w src/lib.rs. Wtedy skrzynia binarna będzie miała dostęp do wszystkich jego publiczne elementów, rozpoczynając ich ścieżki od nazwy pakietu. Skrzynia binarna może użytkować skrzynię biblioteczną na takich samych zasadach jak skrzynia całkowicie zewnętrzna, tj. może korzystać tylko z publicznego interfejsu API. To pomaga zaprojektować dobry interfejs API; jesteś nie tylko jego autorem, ale także użytkownikiem!

W rozdziale 12 zademonstrujemy taką organizację na przykładzie programu wiersza poleceń.

Rozpoczynanie Ścieżek Względnych Od super

Możemy skonstruować względne ścieżki, które zaczynają się w module nadrzędnym, a nie w bieżącym lub korzeniu skrzyni, poprzez użycie super na początku ścieżki. To tak jakby rozpocząć ścieżkę systemu plików od ... Użycie super pozwala odwołać się do elementu znajdującego się w module nadrzędnym i ułatwia modyfikację drzewa modułów, gdy moduł jest ściśle związany ze swoim modułem nadrzędnym, który chcemy przenieść w inne miejsce drzewa.

Rozważmy kod z listingu 7-8, który modeluje sytuację, w której szef kuchni naprawia błędne zamówienie i osobiście przynosi je klientowi. Funkcja fix_incorrect_order zdefiniowana w module back_of_house wywołuje funkcję deliver_order zdefiniowaną w module nadrzędnym, rozpoczynając ścieżkę do deliver_order od super:

Plik: src/lib.rs

fn deliver_order() {}

mod back_of_house {
    fn fix_incorrect_order() {
        cook_order();
        super::deliver_order();
    }

    fn cook_order() {}
}

Listing 7-8: Wywołanie funkcji przy użyciu ścieżki względnej zaczynającej się od super

Funkcja fix_incorrect_order znajduje się w module back_of_house. Za pomocą super osiągamy jego modułu nadrzędny, którym w tym przypadku jest crate, czyli korzeń. W nim zaś odnajdujemy deliver_order. Sukces!!! Zakładamy, że podczas ewentualnej reorganizację drzewa modułów skrzyni, moduł back_of_house i funkcja deliver_order prawdopodobnie zachowają względem siebie tę samą relację i zostaną przeniesione razem. Dlatego użyliśmy super, abyśmy mieli mniej miejsc do zaktualizowania, jeśli ten kod zostanie przeniesiony w przyszłości do innego modułu.

Upublicznianie Struktur i Typów Wyliczeniowych

Możemy również użyć pub by oznaczyć struktury i enumy jako publiczne. Wiążą się z tym jednak pewne dodatkowe szczegóły. Jeśli użyjemy pub przed definicją struktury, uczynimy ją publiczną, ale jej pola pozostaną prywatne. W zależności od potrzeb, możemy uczynić każde z pól publicznym lub nie. Na listingu 7-9 zdefiniowano publiczną strukturę back_of_house::Breakfast, której pole toast jest publiczne, zaś seasonal_fruit prywatne. To modeluje restaurację, w której klient może wybrać rodzaj dołączonego do posiłku chleba, ale szef kuchni decyduje o tym, jakie owoce towarzyszą posiłkowi na podstawie tego, co akurat jest w sezonie i na stanie. Dostępne owoce często się zmieniają, więc klienci nie mogą ich wybrać, ani nawet zobaczyć, jakie owoce dostaną.

Plik: 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() {
    // Zamów śniadanie w lecie z tostem żytnim
    let mut meal = back_of_house::Breakfast::summer("Rye");
    // Zmiana zdania na temat tego, jaki chleb chcemy
    meal.toast = String::from("Wheat");
    println!("I'd like {} toast please", meal.toast);

    // Następna linia nie skompiluje się, jeśli ją odkomentujemy;
    // nie możemy bowiem przeglądać ani modyfikować sezonowych owoców,
    // które są dołączone do posiłku
    // meal.seasonal_fruit = String::from("blueberries");
}

Listing 7-9: Struktura, której część pól jest publiczna, zaś część prywatna

Ponieważ w strukturze back_of_house::Breakfast, pole toast jest publiczne, to w eat_at_restaurant jest ono dostępne do zapisu i odczyt przy użyciu notacji kropkowej. Równocześnie nie możemy użyć pola seasonal_fruit w eat_at_restaurant, ponieważ jest ono prywatne. Proszę spróbować odkomentować linię modyfikującą wartość pola seasonal_fruit i zobaczyć do jakiego błędu to doprowadzi!

Inaczej jest w przypadku typów wyliczeniowych. Jeśli uczynimy enum publicznym, to wszystkie jego warianty także staną się publiczne. Wystarczy postawić pub przed słowem kluczowym enum, tak jak pokazano na listingu 7-10.

Plik: src/lib.rs

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;
}

Listing 7-10: Oznaczenie enum jako publicznego, upublicznia też wszystkie jego warianty

Ponieważ upubliczniliśmy enum Appetizer, to możemy używać wariantów Soup i Salad w eat_at_restaurant.

Typ wyliczeniowy, którego nie wszystkie warianty byłyby publiczne, nie byłyby zbyt użyteczny. Równocześnie byłoby denerwujące, gdybyśmy musieli za każdym razem opatrywać wszystkie warianty enuma adnotacją pub. Dlatego domyślnie warianty enuma są publiczne. Inaczej jest ze strukturami, które często są użyteczne, pomimo że ich pola nie są publiczne. Dlatego pola struktury podążają za ogólną zasadą, że wszystko jest domyślnie prywatne, chyba że opatrzone jest adnotacją pub.

Jest jeszcze jedna nieomówiona kwestia związana z pub, która związana jest z ostatnią funkcjonalnością systemu modułów pozostałą do opisania, czyli ze słowem kluczowym use. Najpierw omówimy use samo w sobie, a następnie pokażemy jak połączyć pub i use.

Włączanie Ścieżek do Zasięgu za Pomocą Słowa Kluczowego use

Konieczność ciągłego wypisywania ścieżek, by wywołyć funkcję może być uciążliwa. Na listingu 7-7, niezależnie od tego, czy wybraliśmy bezwzględną czy względną ścieżkę do funkcji add_to_waitlist, za każdym razem, wywołując ją, musieliśmy napisać także front_of_house i hosting. Na szczęście istnieje sposób na uproszczenie tego procesu: możemy raz utworzyć skrót do ścieżki za pomocą słowa kluczowego use i używać go wielokrotnie w obrębie zasięgu.

Na listingu 7-11 włączamy moduł crate::front_of_house::hosting w zasięg funkcji eat_at_restaurant, więc musimy podać jedynie hosting::add_to_waitlist, aby wywołać funkcję add_to_waitlist z eat_at_restaurant.

Plik: 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();
}

Listing 7-11: Włączanie modułu w zasięg za pomocą use

Dodanie do zasięgu use i ścieżki jest podobne do tworzenia dowiązania symbolicznego w systemie plików. Dodanie use crate::front_of_house::hosting w korzeniu skrzyni sprawia, że hosting staje się poprawną nazwą w tym zasięgu, tak jakby moduł hosting był zdefiniowany w korzeniu skrzyni. Ścieżki wprowadzone w zasięg za pomocą use podlegają takim samym zasadą prywatność, jak wszystkie inne ścieżki.

Warto podkreślić, że use tworzy skrót tylko w zasięgu, w którym występuje. Na listingu 7-12 przeniesiono funkcję eat_at_restaurant do nowego modułu podrzędnego o nazwie customer, który tworzy zasięg odrębny od tego, w którym użyto use. Dlatego ciało funkcji nie skompiluje się:

Plik: 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();
    }
}

Listing 7-12: use obowiązuje jedynie w zasięgu, w którym się znajduje

Błąd kompilatora pokazuje, że skrót nie ma zastosowania w obrębie modułu 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

Proszę zauważyć, że pojawiło się również ostrzeżenie, że use nie jest używany w swoim zasięgu! Aby rozwiązać ten problem, należy przenieść use do modułu customer, lub z modułu customer odwołać się do skrótu w module nadrzędnym za pomocą super::hosting.

Tworzenie Idiomatycznych Ścieżek use

Patrząc na listing 7-11, można się zastanawiać, dlaczego zdefiniowaliśmy use crate::front_of_house::hosting, a następnie w eat_at_restaurant wywołaliśmy hosting::add_to_waitlist, zamiast od razu podać w use całą ścieżkę do add_to_waitlist, tak jak na listingu 7-13.

Plik: 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();
}

Listing 7-13: Nieidiomatyczne włączenie w zasięg funkcji add_to_waitlist za pomocą use

Działanie kodu na obu listingach, 7-11 i 7-13, jest takie samo. Jednakże tylko listing 7-11 pokazuje idiomatyczne wykorzystanie use do włączenia funkcji w zasięg. Włączenie do zasięgu jej modułu nadrzędnego sprawia, że wywołując tę funkcję musimy podać nazwę jej modułu. To zaś jasno mówi, iż funkcja ta nie jest zdefiniowana lokalnie, a jednocześnie ogranicza konieczność podawania pełnej ścieżki. Dla odmiany kod na listingu 7-13 jest niejasny co do miejsca, w którym zdefiniowano add_to_waitlist.

Z drugiej strony, gdy za pomocą use wskazujemy struktury, enumy i inne elementy, idiomatycznie jest podać pełną ścieżkę. Listing 7-14 pokazuje idiomatyczny sposób włączania w zasięg skrzyni binarnej struktury HashMap z biblioteki standardowej.

Plik: src/main.rs

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(1, 2);
}

Listing 7-14: Idiomatyczne włączenie HashMap w zasięg

Za tym idiomem nie stoi żaden mocny argument: jest to po prostu przyjęta konwencja, zaś ludzie przyzwyczaili się do czytania i pisania zgodnego z nią kodu.

Jednakże nie możemy podążyć za tą konwencją, gdy za pomocą use chcemy wprowadzić w zasięg dwa elementy o tej samej nazwie. Rust nam na to nie pozwoli. Listing 7-15 pokazuje, jak włączyć w zasięg i odwoływać się do dwóch typów Result, które mają tę samą nazwę, ale pochodzą z różnych modułów.

Plik: src/lib.rs

use std::fmt;
use std::io;

fn function1() -> fmt::Result {
    // --snip--
    Ok(())
}

fn function2() -> io::Result<()> {
    // --snip--
    Ok(())
}

Listing 7-15: Wprowadzenie w ten sam zasięg dwóch typów o tej samej nazwie wymaga określania ich przy użyciu ich modułów nadrzędnych.

Jak widać, używanie modułów nadrzędnych pozwala rozróżnić dwa typy Result. Gdybyśmy zamiast tego napisali use std::fmt::Result i use std::io::Result, mielibyśmy w tym samym zasięgu dwa różne typy Result i Rust nie wiedziałby, który z nich mamy na myśli, gdy piszemy Result.

Nadawanie Nowych Nazw Za Pomocą Słowa Kluczowego as

Istnieje też inne rozwiązanie problemu wprowadzania dwóch typów o tej samej nazwie w ten sam zasięg za pomocą use: po ścieżce możemy podać as i nową nazwę lokalną, alias dla typu. Listing 7-16 pokazuje kod równoważny temu z listingu 7-15, ale wykorzystujący zmianę nazwy jednego z dwóch typów Result przy użyciu as.

Plik: src/lib.rs

use std::fmt::Result;
use std::io::Result as IoResult;

fn function1() -> Result {
    // --snip--
    Ok(())
}

fn function2() -> IoResult<()> {
    // --snip--
    Ok(())
}

Listing 7-16: Zmiana nazwy typu za pomocą słowa kluczowego as, gdy jest on włączany w zasięg

W drugiej deklaracji use typowi std::io::Result nadajemy nową nazwę IoResult, niekolidującą z nazwą Result z std::fmt, którą również włączamy w ten sam zasięg. Kod pokazany na obu listingach, 7-15 i 7-16, uważany jest za idiomatyczny. Więc w takim przypadku wybór zależy jedynie od naszych osobistych preferencji!

Re-eksportowanie Nazw Za Pomocą pub use

Kiedy za pomocą słowa kluczowego use włączamy nazwę w zasięg, to w nowym zasięgu jest ona prywatna. Aby kodowi wywołującemu nasz kod umożliwić odwołanie się do tej nazwy tak, jakby była zdefiniowana w jego zasięgu, możemy połączyć pub i use. Technika ta nazywana jest reeksportem, ponieważ wprowadzamy element w zasięg, ale również udostępniamy ten element innym, by mogli go włączyć w swój zasięg.

Listing 7-17 pokazuje kod z listingu 7-11 z zmienionym use w module głównym na 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();
}

Listing 7-17: Wykorzystanie pub use by udostępnić nazwę do użycia przez dowolny kod z nowego zasięgu

Przed zmianą, zewnętrzny kod, by wywołać funkcję add_to_waitlist, musiałby użyć ścieżki restaurant::front_of_house::hosting::add_to_waitlist(). Po zmianie, gdy pub use reeksportował moduł hosting z modułu głównego, zewnętrzny kod może w zamian użyć ścieżki restaurant::hosting::add_to_waitlist().

Reeksportowanie jest przydatne, gdy wewnętrzna struktura twojego kodu różni się od tego, jak wywołujący go programiści postrzegają jego domenę. Na przykład w naszej metaforze restauracyjnej, ludzie prowadzący restaurację dzielą ją na „front of house“ i „back of house“. Ale klienci odwiedzający restaurację prawdopodobnie nie będą myśleć o częściach restauracji w ten sam sposób. Dzięki pub use, możemy napisać nasz kod korzystając z innej struktury, od tej, którą ujawnimy. Czynimy to, by nasza biblioteka była dobrze zorganizowana zarówno dla programistów pracujących nad nią, jak i tych ją wywołujących. Przyjrzymy się innemu przykładowi pub use i temu, jak wpływa on na dokumentację skrzyni w sekcji „Eksportowanie Wygodnego Publicznego API Za Pomocą pub use rozdziału 14.

Używanie Pakietów Zewnętrznych

W rozdziale 2 zaprogramowaliśmy grę w zgadywanie, która wykorzystywała zewnętrzny pakiet o nazwie rand do uzyskiwania liczb losowych. Aby użyć rand w naszym projekcie, dodaliśmy następującą linię do Cargo.toml:

Plik: Cargo.toml

rand = "0.8.5"

Dodanie rand jako zależności w Cargo.toml powoduje, że Cargo pobiera pakiet rand wraz ze wszystkimi jego zależnościami z crates.io i udostępnia rand naszemu projektowi.

Następnie, aby włączyć definicje z rand w zasięg naszego pakietu, dodaliśmy linię use ze ścieżką rozpoczynającą się od nazwy skrzyni, czyli rand, i wymieniliśmy elementy, które chcemy włączyć w zasięg. Przypomnijmy, że w sekcji „Generowanie Losowej Liczby“ rozdziału 2, włączyliśmy w zasięg cechę Rng i wywołaliśmy funkcję rand::thread_rng:

use std::io;
use rand::Rng;

fn main() {
    println!("Zgadnij liczbę!");

    let secret_number = rand::thread_rng().gen_range(1..=100);

    println!("Sekretna liczba to: {secret_number}");

    println!("Podaj swoją liczbę:");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Błąd wczytania linii");

    println!("Wybrana przez ciebie liczba: {guess}");
}

Członkowie społeczności Rusta udostępnili na stronie crates.io wiele pakietów, a użycie dowolnego z nich we własnym pakiecie wymaga wykonania tych samych kroków: dodania go do pliku Cargo.toml i włączenia w zasięg jego wybranych elementów za pomocą use.

Proszę zauważyć, że standardowa biblioteka std również jest skrzynią, która jest zewnętrzna względem naszego pakietu. Ponieważ standardowa biblioteka jest dostarczana z językiem Rust, nie musimy dodawać std do Cargo.toml. Musimy jednak odwoływać się do niej za pomocą use, aby wprowadzić jej elementy w zasięg naszego pakietu. Na przykład, możemy skorzystać z HashMap za pomocą następującej linii:

#![allow(unused)]
fn main() {
use std::collections::HashMap;
}

Jest to ścieżka bezwzględna rozpoczynająca się od std, czyli nazwy skrzyni biblioteki standardowej.

Porządkowania Długich List use za Pomocą Zagnieżdżonych Ścieżek

Gdy używamy wielu elementów zdefiniowanych w tej samej skrzyni lub w tym samym module, wymienienie każdego elementu w osobnej linii pochłania sporo miejsca. Na przykład, te dwie deklaracje use, które mieliśmy w grze zgadywance na listingu 2-4, włączają w zasięg elementy z std:

Plik: 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!"),
    }
}

Zamiast nich, możemy użyć zagnieżdżonych ścieżek, aby włączyć te same elementy w jednym wierszu. Robimy to, podając wspólną część ścieżki, po której następują dwa dwukropki, a następnie nawiasy klamrowe obejmujące listę różniących się fragmentów ścieżek, co pokazano na listingu 7-18.

Plik: 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!"),
    }
}

Listing 7-18: Podanie ścieżki zagnieżdżonej w celu włączenia w zasięg wielu elementów z tym samym prefiksem

W większych programach, wprowadzenie wielu elementów tej samej skrzyni lub modułu w zasięg przy użyciu zagnieżdżonych ścieżek może znacznie zmniejszyć liczbę napisanych linii use!

Ścieżki można zagnieżdżać na dowolnym poziomie, co jest przydatne przy łączeniu dwóch deklaracji use dzielących podścieżkę. Na przykład, listing 7-19 pokazuje dwie instrukcje use: pierwsza włącza w zasięg std::io, zaś druga std::io::Write.

Plik: src/lib.rs

use std::io;
use std::io::Write;

Listing 7-19: Dwie deklaracje use, z których jedna włącza podścieżkę drugiej

Częścią wspólną tych dwóch ścieżek jest std::io, co daje całą pierwszą ścieżkę. Aby zawrzeć te dwie ścieżki w jednej deklaracji use, można użyć self w zagnieżdżonej ścieżce, tak jak pokazano na listingu 7-20.

Plik: src/lib.rs

use std::io::{self, Write};

Listing 7-20: Zawarcie ścieżek z listingu 7-19 w jednej deklaracji use

Ta linia włącza std::io i std::io::Write w zasięg.

Operator Glob

Jeśli chcemy włączyć w zasięg wszystkie elementy publiczne zdefiniowane w ścieżce, możemy podać tę ścieżkę, a za nią * zwaną operatorem glob:

#![allow(unused)]
fn main() {
use std::collections::*;
}

Ta deklaracja use wprowadza do bieżącego zasięgu wszystkie publiczne elementy zdefiniowane w std::collections. Operatora glob należy używać z rozwagą! Glob może utrudnić ustalenie, które nazwy są w zasięgu i gdzie zostały zdefiniowane.

Operator globy jest często używany podczas testowania, aby wprowadzić wszystko, co jest testowane, do modułu tests; o czym będziemy mówić w sekcji "How to Write Tests" rozdziału 11. Operator glob jest też czasami używany jako część wzorca prelude, opisanego w dokumentacji biblioteki standardowej.

Umieszczanie Modułów w Osobnych Plikach

Jak dotąd, wszystkie przykłady w tym rozdziale definiowały wiele modułów w pojedynczym pliku. Kiedy moduły stają się duże, warto przenieść ich definicje do osobnych plików, aby ułatwić poruszanie się po kodzie.

Na przykład, zacznijmy od kodu z listingu 7-17, który zawiera wiele modułów restauracji. Zamiast trzymać wszystkie moduły w pliku głównym skrzyni, przeniesiemy je do plików. W tym przypadku plikiem głównym skrzyni jest src/lib.rs, ale ta procedura działa również w przypadku skrzyń binarnych, których plikiem głównym jest src/main.rs.

Najpierw przeniesiemy moduł front_of_house do jego własnego pliku. Usuwamy kod modułu front_of_house zawarty w nawiasach klamrowych, pozostawiając tylko deklarację mod front_of_house;, tak że src/lib.rs zawiera kod pokazany na listingu 7-21. Ten kod nie się skompiluje, dopóki nie utworzymy src/front_of_house.rs, o zawartości pokazanej na listingu 7-22.

Plik: src/lib.rs

mod front_of_house;

pub use crate::front_of_house::hosting;

pub fn eat_at_restaurant() {
    hosting::add_to_waitlist();
}

Listing 7-21: Deklaracja modułu front_of_house, którego ciało znajdzie się w src/front_of_house.rs

Następnie umieszczamy kod, który znajdował się w nawiasach klamrowych, w nowym pliku o nazwie src/front_of_house.rs, jak pokazano na Listingu 7-22. Kompilator wie, że ma szukać kodu w tym pliku, ponieważ natrafił w korzeniu skrzyni na deklarację modułu o nazwie front_of_house.

Plik: src/front_of_house.rs

pub mod hosting {
    pub fn add_to_waitlist() {}
}

Listing 7-22: Definicje wewnątrz modułu front_of_house w src/front_of_house.rs

Warto zauważyć, że plik za pomocą deklaracji mod wystarczy załadować w jednym miejscu drzewa modułów. Kiedy kompilator wie, że plik jest częścią projektu (i wie gdzie w drzewie modułów rezyduje kod, ponieważ umieszczono tam deklarację mod), inne pliki w projekcie powinny odwoływać się do kodu załadowanego z pliku używając ścieżki do miejsca, w którym został zadeklarowany, tak jak to zostało opisane w sekcji „Paths for Referring to an Item in the Module Tree“. Innymi słowy, mod nie jest znaną z niektórych języków programowania operacją „include“.

Następnie przeniesiemy moduł hosting do jego własnego pliku. Proces będzie nieco inny, bo hosting jest modułem podrzędnym w stosunku do front_of_house, a nie modułem głównym. Umieścimy plik dla hosting w nowym katalogu, nazwanym zgodnie z jego przodkami w drzewie modułów, czyli w src/front_of_house/.

Przenoszenie hosting rozpoczynamy od zmieniamy src/front_of_house.rs tak, aby zawierał tylko deklarację modułu hosting:

Plik: src/front_of_house.rs

pub mod hosting;

Następnie tworzymy katalog src/front_of_house, a w nim plik hosting.rs zawierający definicje z modułu hosting:

Plik: src/front_of_house/hosting.rs

pub fn add_to_waitlist() {}

Jeśli zamiast tego umieścilibyśmy hosting.rs w katalogu src, to kompilator oczekiwałby, że kod hosting.rs zostanie zadeklarowany w module hosting znajdującym się w korzeniu skrzyni, a nie w module front_of_house. Reguły kompilatora dotyczące tego, które pliki sprawdzać pod kątem kodu poszczególnych modułów, sprawiają, że drzewo modułów jest odzwierciedlone przez katalogi i pliki.

Alternatywne Ścieżki do Plików

Dotychczas omówiliśmy najbardziej idiomatyczne nazewnictwo ścieżek do plików, które używa kompilator Rusta. Ale Rust obsługuje również nazewnictwo w starszym stylu. Kompilator będzie szukał kodu dla modułu front_of_house zadeklarowanego w korzeniu skrzyni, w:

  • src/front_of_house.rs (co omówiliśmy)
  • src/front_of_house/mod.rs (starszy styl, nadal obsługiwany)

Kompilator będzie szukał kodu dla modułu hosting zadeklarowanego w module front_of_house, w:

  • src/front_of_house/hosting.rs (co omówiliśmy)
  • src/front_of_house/hosting/mod.rs (starszy styl, nadal obsługiwany)

Próba użycia obu stylów dla tego samego modułu poskutkuje błędem kompilatora. Używanie mieszanki obu stylów dla różnych modułów w tym samym projekcie jest dozwolone, ale może być mylące dla osób nawigujących po projekcie.

Głównym minusem używania plików o nazwie mod.rs jest to, że może być ich w projekcie wiele. To zaś może prowadzić do pomyłek, gdy kilka z nich będzie równocześnie otwartych w edytorze.

Przenieśliśmy kod każdego modułu do osobnego pliku, ale drzewo modułów nie zmieniło się. Wywołania funkcji w eat_at_restaurant będą działać bez żadnych modyfikacji, mimo że ich definicje znajdują się w różnych plikach. Dzięki tej technice można przenosić moduły do nowych plików w miarę jak rosną ich rozmiary.

Proszę zauważyć, że deklaracja pub use crate::front_of_house::hosting w src/lib.rs również nie uległa zmianie, oraz że use nie ma wpływu na to, które pliki są kompilowane jako część skrzyni. Słowo kluczowe mod deklaruje moduły, a Rust szuka kodu wchodzącego w skład każdego z nich w pliku nazwanym tak jak moduł.

Podsumowanie

Rust pozwala podzielić pakiet na wiele skrzyń, a każdą ze skrzyń na moduły, tak aby można było odwoływać się do elementów zdefiniowanych w jednym module z innego modułu. Pozwalają na to ścieżki bezwzględne i względne. Ścieżki te mogą być włączone w zasięg za pomocą deklaracji use, dzięki czemu można w nim używać krótszej ścieżki, co jest przydatne gdy elementy są używane w nim wielokrotnie. Kod modułu jest domyślnie prywatny, ale można upublicznić jego definicje za pomocą słowa kluczowego pub.

W następnym rozdziale przyjrzymy się niektórym, zawartym w bibliotece standardowej, strukturom danych realizującym kolekcje, które można wykorzystać w swoim starannie zorganizowanym kodzie.

Często Wykorzystywane Kolekcje

Biblioteka standardowa Rusta zawiera wiele bardzo użytecznych struktur danych zwanych kolekcjami. Podczas gdy większość innych typów danych reprezentuje pojedynczą wartość, kolekcje zwykle przechowują ich wiele. Równocześnie, w przeciwieństwie do wbudowanych typów tablic i krotek, kolekcje przechowują dane na stercie. To oznacza, że ilość tych danych nie musi być znana w czasie kompilacji i może rosnąć lub maleć w trakcie działania programu. Każdy rodzaj kolekcji cechują inne możliwości oraz koszty, zaś dobranie odpowiedniej kolekcji do sytuacji jest umiejętnością, której nabycie zwykle zajmuje trochę czasu. W tym rozdziale omówimy trzy kolekcje, które są bardzo często wykorzystywane w programach napisanych w Ruście:

  • Wektor (vector) przechowuje pewną liczbę wartości, jedna obok drugiej.
  • Łańcuch (string) jest kolekcją znaków. O typie String wspominaliśmy już wcześniej, ale w tym rozdziale omówimy go dogłębnie.
  • Mapa haszująca (hash map) wiąże wartości z kluczami, stanowiąc tym samym szczególną implementację bardziej ogólnej struktury danych zwanej mapą.

Informacje na temat innych rodzai kolekcji zawartych w bibliotece standardowej, można znaleźć w jej dokumentacji.

Omówimy, jak tworzyć i aktualizować wektory, łańcuchy i mapy haszujące, a także co czyni każdą z tych kolekcji wyjątkową.

Przechowywanie List Wartości w Wektorach

Pierwszym typem kolekcji, któremu się przyjrzymy jest Vec<T>, znany również jako wektor. Wektory pozwalają przechować pewną liczbę wartości, umieszczając je w pamięci jedna obok drugiej. Wektory mogą zawierać tylko wartości tego samego typu. Są one przydatne, gdy mamy listę elementów, takich jak linie tekstu z pliku lub ceny towarów w koszyku zakupowym.

Tworzenie Nowego Wektora

Aby utworzyć nowy pusty wektor, wywołujemy funkcję Vec::new, tak jak pokazano na Listingu 8-1.

fn main() {
    let v: Vec<i32> = Vec::new();
}

Listing 8-1: Utworzenie nowego, pustego wektora do przechowywania wartości typu i32

Proszę zauważyć, że dodaliśmy w kodzie adnotację typu. Ponieważ nie wstawiamy do tego wektora żadnych wartości, Rust nie wie, jakiego rodzaju elementy zamierzamy przechowywać. Co zaś istotne, wektory są implementowane z wykorzystaniem generyczności; w rozdziale 10 opowiem jak jej użyć we własnych typach. Na razie wystarczy wiedzieć, że typ Vec<T> z biblioteki standardowej może przechowywać elementy dowolnego, zadanego typu. Ten typ możemy wskazać w nawiasach kątowych podczas tworzenia wektora. Na listingu 8-1 powiedzieliśmy Rustowi, że Vec<T> w v będzie przechowywał elementy typu i32.

Zazwyczaj jednak Vec<T> będzie tworzony z wartościami początkowymi i Rust wywnioskuje typ przechowywanej wartości. Adnotacja typu nie będzie wtedy wymagana. Rust dostarcza wygodne makro vec!, tworzące nowy wektor z podanymi wartościami. Przykładowo, na listing 8-2 tworzony jest Vec<i32> zawierający 1, 2, i 3. Typem wartości jest tam i32, ponieważ jest to domyślny typ dla liczb całkowitych, co omówiliśmy w sekcji „Typy danych“ rozdziału 3.

fn main() {
    let v = vec![1, 2, 3];
}

Listing 8-2: Tworzenie nowego wektora zawierającego wartości

Ponieważ podano początkowe wartości typu i32, to Rust może wywnioskować, że typem v jest Vec<i32>, nawet bez adnotacji typu. Za chwilę omówimy, jak modyfikować wektor.

Uaktualnianie Wektora

Listing 8-3 pokazuje jak utworzyć wektor, a następnie dodać do niego elementy za pomocą metody push.

fn main() {
    let mut v = Vec::new();

    v.push(5);
    v.push(6);
    v.push(7);
    v.push(8);
}

Listing 8-3: Dodawanie elementów do wektora za pomocą metody push

Jak w przypadku każdej zmiennej, jeśli chcemy mieć możliwość zmiany jej wartości, musimy uczynić ją mutowalną za pomocą słowa kluczowego mut, tak jak zostało to omówione w rozdziale 3. Ponieważ wszystkie dodawane liczby są typu i32, to Rust wywnioskuje odpowiedni typ wektora, nawet bez adnotacji Vec<i32>.

Czytanie Elementów Wektora

Istnieją dwa sposoby odwołania się do wartości przechowywanej w wektorze: poprzez indeksowanie lub użycie metody get. W poniższych przykładach, dla przejrzystości, opatrzyliśmy adnotacjami typy wartości zwracanych przez te funkcje.

Listing 8-4 pokazuje obie metody dostępu do wartości w wektorze. Pierwsza wykorzystuje składnie indeksowania, druga zaś metodę 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."),
    }
}

Listing 8-4: Użycie indeksowania lub metody get by uzyskać dostęp do elementu w wektorze

W tym miejscu warto zwrócić uwagę na kilka szczegółów. Ponieważ wektory są indeksowane od zera, to by uzyskać trzeci element, używamy indeksu 2. Użycie & i [] daje referencję do elementu znajdującego się pod zadanym indeksem. Metoda get, której argumentem jest żądany indeks, zwraca Option<&T>, który możemy użyć z match.

Powodem, dla którego Rust udostępnia dwa sposoby odwoływania się do elementu, jest danie możliwość wyboru, jak ma zachować się program, podczas próby użycia indeksu spoza zakresu indeksów istniejących elementów. Na przykład zobaczmy co się stanie, gdy za pomocą każdej z tych technik spróbujemy uzyskać dostęp do elementu o indeksie 100 z wektora o pięciu elementach, jak pokazano na listingu 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);
}

Listing 8-5: Próba uzyskania dostęp do elementu o indeksie 100 z wektora o pięciu elementach

Kiedy uruchomimy ten kod, odwołanie się do nieistniejącego elementu pierwszą metodą [] spowoduje, że program spanikuje. Tej metody najlepiej więc użyć, gdy chcemy, aby podczas próby dostępu do elementu poza końcem wektora, program został zakończony.

Dla odmiany metoda get wywołana z nieistniejącym indeksem nie panikuje, tylko zwraca None. To przydaje się, gdy sporadyczny dostęp do elementu poza zakresem wektora jest spodziewany. Należy wtedy wyposażyć kod w logikę obsługującą oba możliwe rezultaty tej metody, zarówno Some(&element) jak i None, tak jak to omówiono w rozdziale 6. Na przykład, indeks może pochodzić od osoby wprowadzającej numer. Jeśli przypadkowo wprowadzi ona zbyt dużą liczbę i program otrzyma wartość None, można zakomunikować ile elementów znajduje się w bieżącym wektorze i dać użytkownikowi kolejną szansę na wprowadzenie poprawnej wartości. Będzie to dla niego bardziej przyjazne niż zakończenie programu z powodu literówki!

Nadzorca pożyczania, egzekwując zasady własności i reguły pożyczania (omówione w rozdziale 4), zapewni że wszelkie reference do zawartości wektora, będą poprawne. Proszę przypomnieć sobie regułę mówiącą, że nie można mieć mutowalnych i niemutowalnych referencji w tym samym zasięgu. Ta zasada ujawnia się na listingu 8-6, gdzie trzymając niemutowalną referencję do pierwszego elementu wektora, próbujemy dodać element na jego koniec. Jeśli dodatkowo spróbujemy odwołać się do tego elementu w dalszej części funkcji, to ten program się nie skompiluje:

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];

    let first = &v[0];

    v.push(6);

    println!("The first element is: {first}");
}

Listing 8-6: Próba dodania do wektora, do którego elementu trzymamy referencję

Próba skompilowania tego kodu daje następujący błąd:

$ 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

Wydaje się, że kod na listingu 8-6 powinien działać: dlaczego referencja do pierwszego elementu miałaby się przejmować zmianami na końcu wektora? Błąd wynika ze sposobu działania wektorów: ponieważ wektory umieszczają wartości w pamięci obok siebie, to dodanie nowego elementu na końcu wektora może wymagać przydzielenia nowej pamięci i skopiowania do niej uprzednio dodanych elementów, gdy zabraknie miejsca tam, gdzie są one obecnie przechowywane. W takim przypadku referencja do pierwszego elementu wskazywałaby na zwolniony obszar pamięci. Zaś reguły pożyczania uniemożliwiają doprowadzenie programu do takiej sytuacji.

Uwaga: Więcej o implementacji typu Vec<T> można znaleźć w “The Rustonomicon”.

Iterowanie po Zawartych w Wektorze Wartościach

Aby uzyskać dostęp kolejno do wszystkich elementów wektora, to zamiast używać ich indeksów, lepiej go przeiterować. Listing 8-7 pokazuje, jak za pomocą pętli for uzyskać niemutowalne referencje do wszystkich liczb (typu i32) zawartych w wektorze i te liczby wypisać.

fn main() {
    let v = vec![100, 32, 57];
    for i in &v {
        println!("{i}");
    }
}

Listing 8-7: Wypisanie zawartości wektora za pomocą pętli for iterującej po jego elementach

Iterując po mutowalnych referencjach do elementów, możemy również zmodyfikować wszystkie elementy mutowalnego wektora. Pętla for na listingu 8-8 dodaje do każdego 50.

fn main() {
    let mut v = vec![100, 32, 57];
    for i in &mut v {
        *i += 50;
    }
}

Listing 8-8: Iterowanie po mutowalnych referencjach do elementów wektora

Aby za pomocą operatora += zmienić wartość, do której odnosi się mutowalna referencja i, wpierw musimy się do tej wartości dostać za pomocą operatora dereferencji *. Więcej o operatorze dereferencji powiemy w sekcji "Following the Pointer to the Value with the Dereference Operator" rozdziału 15.

Dzięki regułom nadzorcy pożyczania, zarówno niemutowalne jak i mutowalne iterowanie po wektorze, jest bezpieczne. Gdybyśmy na listingu 8-7 lub 8-8 spróbowali w ciałach pętli for wstawiać do wektora elementy lub je usuwać, otrzymalibyśmy błąd kompilatora podobny do tego, który powodował kod na listingu 8-6. Ponieważ pętla for posiada referencję do wektora, to nie można go równocześnie modyfikować inaczej, niż poprzez tę referencję.

Przechowywanie Wartości Różnych Typów za Pomocą Typu Wyliczeniowego

Wektory mogą przechowywać tylko wartości tego samego typu, co może być uciążliwe; nierzadko zdarza się potrzeba przechowani listy elementów różnych typów. Na szczęście warianty wyliczenia są zdefiniowane w ramach tego samego typu enum, więc kiedy potrzebujemy jednego typu do reprezentowania elementów różnych typów, możemy zdefiniować i użyć enuma!

Na przykład, załóżmy, że chcemy uzyskać wartości z wiersza arkusza kalkulacyjnego, w którym niektóre kolumny w wierszu zawierają liczby całkowite, niektóre liczby zmiennoprzecinkowe, zaś niektóre łańcuchy. Możemy zdefiniować typ wyliczeniowy, którego warianty będą trzymać wartości różnych typów, a jednocześnie wszystkie te warianty będą traktowane jako ten sam typ. Następnie możemy utworzyć wektor takich enumów, efektywnie przechowujący wartości różnych typów. Takie działanie ilustruje 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),
    ];
}

Listing 8-9: Zdefiniowanie enum do przechowywania wartości różnych typów w jednym wektorze

Rust już w czasie kompilacji musi wiedzieć, jakiego typu elementy są dozwolone w wektorze, aby dokładnie przewidzieć, ile pamięci na stercie będzie potrzebne do ich przechowania. Dlatego musimy jednoznacznie te typy określić. Gdyby Rust pozwolił wektorowi przechowywać elementy dowolnych typów, istniałoby zagrożenie, że jeden lub więcej typów spowodowałoby błędy w operacjach wykonywanych na elementach wektora. Użycie enum plus wyrażenia match oznacza, że Rust zapewni w czasie kompilacji, że każdy możliwy przypadek zostanie obsłużony, jak omówiono w rozdziale 6.

Gdybyśmy nie znali wyczerpującego zestawu typów, których wartości w czasie wykonywania programu będą dodawane do wektora, to nie moglibyśmy użyć omówionej techniki wykorzystującej enum. Instead, you can use a trait object, which we’ll cover in Chapter 17.

Teraz, gdy omówiliśmy wybrane, częste sposoby używania wektorów, warto przejrzeć dokumentację API, gdyż zawarty w bibliotece standardowej Vec<T> posiada znacznie więcej użytecznych metod. Na przykład jego metoda pop usuwa i zwraca ostatni element.

Wraz z Wektorem Zwalniane Są Jego Elementy

Jak każda inna struktura, wektor jest zwalniany gdy wychodzi poza zasięg, jak to zostało zaznaczone na listingu 8-10.

fn main() {
    {
        let v = vec![1, 2, 3, 4];

        // do stuff with v
    } // <- v goes out of scope and is freed here
}

Listing 8-10: Pokazanie, gdzie jest zwalniany wektor i jego elementy

Gdy wektor jest zwalniany, cała jego zawartość również jest zwalniana, co oznacza usunięcie z pamięci przechowywanych w nim liczb. Nadzorca pożyczania nie pozwoli używać żadnych referencji do zawartości wektora, który utracił ważność.

Przejdźmy do kolejnego typu kolekcji: Stringa!

Storing UTF-8 Encoded Text with Strings

We talked about strings in Chapter 4, but we’ll look at them in more depth now. New Rustaceans commonly get stuck on strings for a combination of three reasons: Rust’s propensity for exposing possible errors, strings being a more complicated data structure than many programmers give them credit for, and UTF-8. These factors combine in a way that can seem difficult when you’re coming from other programming languages.

We discuss strings in the context of collections because strings are implemented as a collection of bytes, plus some methods to provide useful functionality when those bytes are interpreted as text. In this section, we’ll talk about the operations on String that every collection type has, such as creating, updating, and reading. We’ll also discuss the ways in which String is different from the other collections, namely how indexing into a String is complicated by the differences between how people and computers interpret String data.

What Is a String?

We’ll first define what we mean by the term string. Rust has only one string type in the core language, which is the string slice str that is usually seen in its borrowed form &str. In Chapter 4, we talked about string slices, which are references to some UTF-8 encoded string data stored elsewhere. String literals, for example, are stored in the program’s binary and are therefore string slices.

The String type, which is provided by Rust’s standard library rather than coded into the core language, is a growable, mutable, owned, UTF-8 encoded string type. When Rustaceans refer to “strings” in Rust, they might be referring to either the String or the string slice &str types, not just one of those types. Although this section is largely about String, both types are used heavily in Rust’s standard library, and both String and string slices are UTF-8 encoded.

Creating a New String

Many of the same operations available with Vec<T> are available with String as well, because String is actually implemented as a wrapper around a vector of bytes with some extra guarantees, restrictions, and capabilities. An example of a function that works the same way with Vec<T> and String is the new function to create an instance, shown in Listing 8-11.

fn main() {
    let mut s = String::new();
}

Listing 8-11: Creating a new, empty String

This line creates a new empty string called s, which we can then load data into. Often, we’ll have some initial data that we want to start the string with. For that, we use the to_string method, which is available on any type that implements the Display trait, as string literals do. Listing 8-12 shows two examples.

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();
}

Listing 8-12: Using the to_string method to create a String from a string literal

This code creates a string containing initial contents.

We can also use the function String::from to create a String from a string literal. The code in Listing 8-13 is equivalent to the code from Listing 8-12 that uses to_string.

fn main() {
    let s = String::from("initial contents");
}

Listing 8-13: Using the String::from function to create a String from a string literal

Because strings are used for so many things, we can use many different generic APIs for strings, providing us with a lot of options. Some of them can seem redundant, but they all have their place! In this case, String::from and to_string do the same thing, so which you choose is a matter of style and readability.

Remember that strings are UTF-8 encoded, so we can include any properly encoded data in them, as shown in 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");
}

Listing 8-14: Storing greetings in different languages in strings

All of these are valid String values.

Updating a String

A String can grow in size and its contents can change, just like the contents of a Vec<T>, if you push more data into it. In addition, you can conveniently use the + operator or the format! macro to concatenate String values.

Appending to a String with push_str and push

We can grow a String by using the push_str method to append a string slice, as shown in Listing 8-15.

fn main() {
    let mut s = String::from("foo");
    s.push_str("bar");
}

Listing 8-15: Appending a string slice to a String using the push_str method

After these two lines, s will contain foobar. The push_str method takes a string slice because we don’t necessarily want to take ownership of the parameter. For example, in the code in Listing 8-16, we want to be able to use s2 after appending its contents to s1.

fn main() {
    let mut s1 = String::from("foo");
    let s2 = "bar";
    s1.push_str(s2);
    println!("s2 is {s2}");
}

Listing 8-16: Using a string slice after appending its contents to a String

If the push_str method took ownership of s2, we wouldn’t be able to print its value on the last line. However, this code works as we’d expect!

The push method takes a single character as a parameter and adds it to the String. Listing 8-17 adds the letter “l” to a String using the push method.

fn main() {
    let mut s = String::from("lo");
    s.push('l');
}

Listing 8-17: Adding one character to a String value using push

As a result, s will contain lol.

Concatenation with the + Operator or the format! Macro

Often, you’ll want to combine two existing strings. One way to do so is to use the + operator, as shown in 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
}

Listing 8-18: Using the + operator to combine two String values into a new String value

The string s3 will contain Hello, world!. The reason s1 is no longer valid after the addition, and the reason we used a reference to s2, has to do with the signature of the method that’s called when we use the + operator. The + operator uses the add method, whose signature looks something like this:

fn add(self, s: &str) -> String {

In the standard library, you'll see add defined using generics and associated types. Here, we’ve substituted in concrete types, which is what happens when we call this method with String values. We’ll discuss generics in Chapter 10. This signature gives us the clues we need to understand the tricky bits of the + operator.

First, s2 has an &, meaning that we’re adding a reference of the second string to the first string. This is because of the s parameter in the add function: we can only add a &str to a String; we can’t add two String values together. But wait—the type of &s2 is &String, not &str, as specified in the second parameter to add. So why does Listing 8-18 compile?

The reason we’re able to use &s2 in the call to add is that the compiler can coerce the &String argument into a &str. When we call the add method, Rust uses a deref coercion, which here turns &s2 into &s2[..]. We’ll discuss deref coercion in more depth in Chapter 15. Because add does not take ownership of the s parameter, s2 will still be a valid String after this operation.

Second, we can see in the signature that add takes ownership of self, because self does not have an &. This means s1 in Listing 8-18 will be moved into the add call and will no longer be valid after that. So although let s3 = s1 + &s2; looks like it will copy both strings and create a new one, this statement actually takes ownership of s1, appends a copy of the contents of s2, and then returns ownership of the result. In other words, it looks like it’s making a lot of copies but isn’t; the implementation is more efficient than copying.

If we need to concatenate multiple strings, the behavior of the + operator gets unwieldy:

fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = s1 + "-" + &s2 + "-" + &s3;
}

At this point, s will be tic-tac-toe. With all of the + and " characters, it’s difficult to see what’s going on. For more complicated string combining, we can instead use the format! macro:

fn main() {
    let s1 = String::from("tic");
    let s2 = String::from("tac");
    let s3 = String::from("toe");

    let s = format!("{s1}-{s2}-{s3}");
}

This code also sets s to tic-tac-toe. The format! macro works like println!, but instead of printing the output to the screen, it returns a String with the contents. The version of the code using format! is much easier to read, and the code generated by the format! macro uses references so that this call doesn’t take ownership of any of its parameters.

Indexing into Strings

In many other programming languages, accessing individual characters in a string by referencing them by index is a valid and common operation. However, if you try to access parts of a String using indexing syntax in Rust, you’ll get an error. Consider the invalid code in Listing 8-19.

fn main() {
    let s1 = String::from("hello");
    let h = s1[0];
}

Listing 8-19: Attempting to use indexing syntax with a String

This code will result in the following error:

$ 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

The error and the note tell the story: Rust strings don’t support indexing. But why not? To answer that question, we need to discuss how Rust stores strings in memory.

Internal Representation

A String is a wrapper over a Vec<u8>. Let’s look at some of our properly encoded UTF-8 example strings from Listing 8-14. First, this one:

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 this case, len will be 4, which means the vector storing the string “Hola” is 4 bytes long. Each of these letters takes 1 byte when encoded in UTF-8. The following line, however, may surprise you. (Note that this string begins with the capital Cyrillic letter Ze, not the Arabic number 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");
}

Asked how long the string is, you might say 12. In fact, Rust’s answer is 24: that’s the number of bytes it takes to encode “Здравствуйте” in UTF-8, because each Unicode scalar value in that string takes 2 bytes of storage. Therefore, an index into the string’s bytes will not always correlate to a valid Unicode scalar value. To demonstrate, consider this invalid Rust code:

let hello = "Здравствуйте";
let answer = &hello[0];

You already know that answer will not be З, the first letter. When encoded in UTF-8, the first byte of З is 208 and the second is 151, so it would seem that answer should in fact be 208, but 208 is not a valid character on its own. Returning 208 is likely not what a user would want if they asked for the first letter of this string; however, that’s the only data that Rust has at byte index 0. Users generally don’t want the byte value returned, even if the string contains only Latin letters: if &"hello"[0] were valid code that returned the byte value, it would return 104, not h.

The answer, then, is that to avoid returning an unexpected value and causing bugs that might not be discovered immediately, Rust doesn’t compile this code at all and prevents misunderstandings early in the development process.

Bytes and Scalar Values and Grapheme Clusters! Oh My!

Another point about UTF-8 is that there are actually three relevant ways to look at strings from Rust’s perspective: as bytes, scalar values, and grapheme clusters (the closest thing to what we would call letters).

If we look at the Hindi word “नमस्ते” written in the Devanagari script, it is stored as a vector of u8 values that looks like this:

[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164,
224, 165, 135]

That’s 18 bytes and is how computers ultimately store this data. If we look at them as Unicode scalar values, which are what Rust’s char type is, those bytes look like this:

['न', 'म', 'स', '्', 'त', 'े']

There are six char values here, but the fourth and sixth are not letters: they’re diacritics that don’t make sense on their own. Finally, if we look at them as grapheme clusters, we’d get what a person would call the four letters that make up the Hindi word:

["न", "म", "स्", "ते"]

Rust provides different ways of interpreting the raw string data that computers store so that each program can choose the interpretation it needs, no matter what human language the data is in.

A final reason Rust doesn’t allow us to index into a String to get a character is that indexing operations are expected to always take constant time (O(1)). But it isn’t possible to guarantee that performance with a String, because Rust would have to walk through the contents from the beginning to the index to determine how many valid characters there were.

Slicing Strings

Indexing into a string is often a bad idea because it’s not clear what the return type of the string-indexing operation should be: a byte value, a character, a grapheme cluster, or a string slice. If you really need to use indices to create string slices, therefore, Rust asks you to be more specific.

Rather than indexing using [] with a single number, you can use [] with a range to create a string slice containing particular bytes:

#![allow(unused)]
fn main() {
let hello = "Здравствуйте";

let s = &hello[0..4];
}

Here, s will be a &str that contains the first 4 bytes of the string. Earlier, we mentioned that each of these characters was 2 bytes, which means s will be Зд.

If we were to try to slice only part of a character’s bytes with something like &hello[0..1], Rust would panic at runtime in the same way as if an invalid index were accessed in a vector:

$ 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

You should use ranges to create string slices with caution, because doing so can crash your program.

Methods for Iterating Over Strings

The best way to operate on pieces of strings is to be explicit about whether you want characters or bytes. For individual Unicode scalar values, use the chars method. Calling chars on “Зд” separates out and returns two values of type char, and you can iterate over the result to access each element:

#![allow(unused)]
fn main() {
for c in "Зд".chars() {
    println!("{c}");
}
}

This code will print the following:

З
д

Alternatively, the bytes method returns each raw byte, which might be appropriate for your domain:

#![allow(unused)]
fn main() {
for b in "Зд".bytes() {
    println!("{b}");
}
}

This code will print the four bytes that make up this string:

208
151
208
180

But be sure to remember that valid Unicode scalar values may be made up of more than 1 byte.

Getting grapheme clusters from strings as with the Devanagari script is complex, so this functionality is not provided by the standard library. Crates are available on crates.io if this is the functionality you need.

Strings Are Not So Simple

To summarize, strings are complicated. Different programming languages make different choices about how to present this complexity to the programmer. Rust has chosen to make the correct handling of String data the default behavior for all Rust programs, which means programmers have to put more thought into handling UTF-8 data upfront. This trade-off exposes more of the complexity of strings than is apparent in other programming languages, but it prevents you from having to handle errors involving non-ASCII characters later in your development life cycle.

The good news is that the standard library offers a lot of functionality built off the String and &str types to help handle these complex situations correctly. Be sure to check out the documentation for useful methods like contains for searching in a string and replace for substituting parts of a string with another string.

Let’s switch to something a bit less complex: hash maps!

Storing Keys with Associated Values in Hash Maps

The last of our common collections is the hash map. The type HashMap<K, V> stores a mapping of keys of type K to values of type V using a hashing function, which determines how it places these keys and values into memory. Many programming languages support this kind of data structure, but they often use a different name, such as hash, map, object, hash table, dictionary, or associative array, just to name a few.

Hash maps are useful when you want to look up data not by using an index, as you can with vectors, but by using a key that can be of any type. For example, in a game, you could keep track of each team’s score in a hash map in which each key is a team’s name and the values are each team’s score. Given a team name, you can retrieve its score.

We’ll go over the basic API of hash maps in this section, but many more goodies are hiding in the functions defined on HashMap<K, V> by the standard library. As always, check the standard library documentation for more information.

Creating a New Hash Map

One way to create an empty hash map is using new and adding elements with insert. In Listing 8-20, we’re keeping track of the scores of two teams whose names are Blue and Yellow. The Blue team starts with 10 points, and the Yellow team starts with 50.

fn main() {
    use std::collections::HashMap;

    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
}

Listing 8-20: Creating a new hash map and inserting some keys and values

Note that we need to first use the HashMap from the collections portion of the standard library. Of our three common collections, this one is the least often used, so it’s not included in the features brought into scope automatically in the prelude. Hash maps also have less support from the standard library; there’s no built-in macro to construct them, for example.

Just like vectors, hash maps store their data on the heap. This HashMap has keys of type String and values of type i32. Like vectors, hash maps are homogeneous: all of the keys must have the same type as each other, and all of the values must have the same type.

Accessing Values in a Hash Map

We can get a value out of the hash map by providing its key to the get method, as shown in Listing 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);
}

Listing 8-21: Accessing the score for the Blue team stored in the hash map

Here, score will have the value that’s associated with the Blue team, and the result will be 10. The get method returns an Option<&V>; if there’s no value for that key in the hash map, get will return None. This program handles the Option by calling copied to get an Option<i32> rather than an Option<&i32>, then unwrap_or to set score to zero if scores doesn't have an entry for the key.

We can iterate over each key/value pair in a hash map in a similar manner as we do with vectors, using a 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}");
    }
}

This code will print each pair in an arbitrary order:

Yellow: 50
Blue: 10

Hash Maps and Ownership

For types that implement the Copy trait, like i32, the values are copied into the hash map. For owned values like String, the values will be moved and the hash map will be the owner of those values, as demonstrated in Listing 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!
}

Listing 8-22: Showing that keys and values are owned by the hash map once they’re inserted

We aren’t able to use the variables field_name and field_value after they’ve been moved into the hash map with the call to insert.

If we insert references to values into the hash map, the values won’t be moved into the hash map. The values that the references point to must be valid for at least as long as the hash map is valid. We’ll talk more about these issues in the “Validating References with Lifetimes” section in Chapter 10.

Updating a Hash Map

Although the number of key and value pairs is growable, each unique key can only have one value associated with it at a time (but not vice versa: for example, both the Blue team and the Yellow team could have value 10 stored in the scores hash map).

When you want to change the data in a hash map, you have to decide how to handle the case when a key already has a value assigned. You could replace the old value with the new value, completely disregarding the old value. You could keep the old value and ignore the new value, only adding the new value if the key doesn’t already have a value. Or you could combine the old value and the new value. Let’s look at how to do each of these!

Overwriting a Value

If we insert a key and a value into a hash map and then insert that same key with a different value, the value associated with that key will be replaced. Even though the code in Listing 8-23 calls insert twice, the hash map will only contain one key/value pair because we’re inserting the value for the Blue team’s key both times.

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);
}

Listing 8-23: Replacing a value stored with a particular key

This code will print {"Blue": 25}. The original value of 10 has been overwritten.

Adding a Key and Value Only If a Key Isn’t Present

It’s common to check whether a particular key already exists in the hash map with a value then take the following actions: if the key does exist in the hash map, the existing value should remain the way it is. If the key doesn’t exist, insert it and a value for it.

Hash maps have a special API for this called entry that takes the key you want to check as a parameter. The return value of the entry method is an enum called Entry that represents a value that might or might not exist. Let’s say we want to check whether the key for the Yellow team has a value associated with it. If it doesn’t, we want to insert the value 50, and the same for the Blue team. Using the entry API, the code looks like Listing 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);
}

Listing 8-24: Using the entry method to only insert if the key does not already have a value

The or_insert method on Entry is defined to return a mutable reference to the value for the corresponding Entry key if that key exists, and if not, inserts the parameter as the new value for this key and returns a mutable reference to the new value. This technique is much cleaner than writing the logic ourselves and, in addition, plays more nicely with the borrow checker.

Running the code in Listing 8-24 will print {"Yellow": 50, "Blue": 10}. The first call to entry will insert the key for the Yellow team with the value 50 because the Yellow team doesn’t have a value already. The second call to entry will not change the hash map because the Blue team already has the value 10.

Updating a Value Based on the Old Value

Another common use case for hash maps is to look up a key’s value and then update it based on the old value. For instance, Listing 8-25 shows code that counts how many times each word appears in some text. We use a hash map with the words as keys and increment the value to keep track of how many times we’ve seen that word. If it’s the first time we’ve seen a word, we’ll first insert the value 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);
}

Listing 8-25: Counting occurrences of words using a hash map that stores words and counts

This code will print {"world": 2, "hello": 1, "wonderful": 1}. You might see the same key/value pairs printed in a different order: recall from the “Accessing Values in a Hash Map” section that iterating over a hash map happens in an arbitrary order.

The split_whitespace method returns an iterator over sub-slices, separated by whitespace, of the value in text. The or_insert method returns a mutable reference (&mut V) to the value for the specified key. Here we store that mutable reference in the count variable, so in order to assign to that value, we must first dereference count using the asterisk (*). The mutable reference goes out of scope at the end of the for loop, so all of these changes are safe and allowed by the borrowing rules.

Hashing Functions

By default, HashMap uses a hashing function called SipHash that can provide resistance to Denial of Service (DoS) attacks involving hash tables1. This is not the fastest hashing algorithm available, but the trade-off for better security that comes with the drop in performance is worth it. If you profile your code and find that the default hash function is too slow for your purposes, you can switch to another function by specifying a different hasher. A hasher is a type that implements the BuildHasher trait. We’ll talk about traits and how to implement them in Chapter 10. You don’t necessarily have to implement your own hasher from scratch; crates.io has libraries shared by other Rust users that provide hashers implementing many common hashing algorithms.

Summary

Vectors, strings, and hash maps will provide a large amount of functionality necessary in programs when you need to store, access, and modify data. Here are some exercises you should now be equipped to solve:

  • Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that occurs most often; a hash map will be helpful here) of the list.
  • Convert strings to pig latin. The first consonant of each word is moved to the end of the word and “ay” is added, so “first” becomes “irst-fay.” Words that start with a vowel have “hay” added to the end instead (“apple” becomes “apple-hay”). Keep in mind the details about UTF-8 encoding!
  • Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.

The standard library API documentation describes methods that vectors, strings, and hash maps have that will be helpful for these exercises!

We’re getting into more complex programs in which operations can fail, so, it’s a perfect time to discuss error handling. We’ll do that next!

Error Handling

Errors are a fact of life in software, so Rust has a number of features for handling situations in which something goes wrong. In many cases, Rust requires you to acknowledge the possibility of an error and take some action before your code will compile. This requirement makes your program more robust by ensuring that you’ll discover errors and handle them appropriately before you’ve deployed your code to production!

Rust groups errors into two major categories: recoverable and unrecoverable errors. For a recoverable error, such as a file not found error, we most likely just want to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, like trying to access a location beyond the end of an array, and so we want to immediately stop the program.

Most languages don’t distinguish between these two kinds of errors and handle both in the same way, using mechanisms such as exceptions. Rust doesn’t have exceptions. Instead, it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error. This chapter covers calling panic! first and then talks about returning Result<T, E> values. Additionally, we’ll explore considerations when deciding whether to try to recover from an error or to stop execution.

Unrecoverable Errors with panic!

Sometimes, bad things happen in your code, and there’s nothing you can do about it. In these cases, Rust has the panic! macro. There are two ways to cause a panic in practice: by taking an action that causes our code to panic (such as accessing an array past the end) or by explicitly calling the panic! macro. In both cases, we cause a panic in our program. By default, these panics will print a failure message, unwind, clean up the stack, and quit. Via an environment variable, you can also have Rust display the call stack when a panic occurs to make it easier to track down the source of the panic.

Unwinding the Stack or Aborting in Response to a Panic

By default, when a panic occurs, the program starts unwinding, which means Rust walks back up the stack and cleans up the data from each function it encounters. However, this walking back and cleanup is a lot of work. Rust, therefore, allows you to choose the alternative of immediately aborting, which ends the program without cleaning up.

Memory that the program was using will then need to be cleaned up by the operating system. If in your project you need to make the resulting binary as small as possible, you can switch from unwinding to aborting upon a panic by adding panic = 'abort' to the appropriate [profile] sections in your Cargo.toml file. For example, if you want to abort on panic in release mode, add this:

[profile.release]
panic = 'abort'

Let’s try calling panic! in a simple program:

Filename: src/main.rs

fn main() {
    panic!("crash and burn");
}

When you run the program, you’ll see something like this:

$ 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

The call to panic! causes the error message contained in the last two lines. The first line shows our panic message and the place in our source code where the panic occurred: src/main.rs:2:5 indicates that it’s the second line, fifth character of our src/main.rs file.

In this case, the line indicated is part of our code, and if we go to that line, we see the panic! macro call. In other cases, the panic! call might be in code that our code calls, and the filename and line number reported by the error message will be someone else’s code where the panic! macro is called, not the line of our code that eventually led to the panic! call. We can use the backtrace of the functions the panic! call came from to figure out the part of our code that is causing the problem. We’ll discuss backtraces in more detail next.

Using a panic! Backtrace

Let’s look at another example to see what it’s like when a panic! call comes from a library because of a bug in our code instead of from our code calling the macro directly. Listing 9-1 has some code that attempts to access an index in a vector beyond the range of valid indexes.

Filename: src/main.rs

fn main() {
    let v = vec![1, 2, 3];

    v[99];
}

Listing 9-1: Attempting to access an element beyond the end of a vector, which will cause a call to panic!

Here, we’re attempting to access the 100th element of our vector (which is at index 99 because indexing starts at zero), but the vector has only 3 elements. In this situation, Rust will panic. Using [] is supposed to return an element, but if you pass an invalid index, there’s no element that Rust could return here that would be correct.

In C, attempting to read beyond the end of a data structure is undefined behavior. You might get whatever is at the location in memory that would correspond to that element in the data structure, even though the memory doesn’t belong to that structure. This is called a buffer overread and can lead to security vulnerabilities if an attacker is able to manipulate the index in such a way as to read data they shouldn’t be allowed to that is stored after the data structure.

To protect your program from this sort of vulnerability, if you try to read an element at an index that doesn’t exist, Rust will stop execution and refuse to continue. Let’s try it and see:

$ 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

This error points at line 4 of our main.rs where we attempt to access index 99. The next note line tells us that we can set the RUST_BACKTRACE environment variable to get a backtrace of exactly what happened to cause the error. A backtrace is a list of all the functions that have been called to get to this point. Backtraces in Rust work as they do in other languages: the key to reading the backtrace is to start from the top and read until you see files you wrote. That’s the spot where the problem originated. The lines above that spot are code that your code has called; the lines below are code that called your code. These before-and-after lines might include core Rust code, standard library code, or crates that you’re using. Let’s try getting a backtrace by setting the RUST_BACKTRACE environment variable to any value except 0. Listing 9-2 shows output similar to what you’ll see.

$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
stack backtrace:
   0: rust_begin_unwind
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/std/src/panicking.rs:584:5
   1: core::panicking::panic_fmt
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/panicking.rs:142:14
   2: core::panicking::panic_bounds_check
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/panicking.rs:84:5
   3: <usize as core::slice::index::SliceIndex<[T]>>::index
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/slice/index.rs:242:10
   4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/slice/index.rs:18:9
   5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/alloc/src/vec/mod.rs:2591:9
   6: panic::main
             at ./src/main.rs:4:5
   7: core::ops::function::FnOnce::call_once
             at /rustc/e092d0b6b43f2de967af0887873151bb1c0b18d3/library/core/src/ops/function.rs:248:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

Listing 9-2: The backtrace generated by a call to panic! displayed when the environment variable RUST_BACKTRACE is set

That’s a lot of output! The exact output you see might be different depending on your operating system and Rust version. In order to get backtraces with this information, debug symbols must be enabled. Debug symbols are enabled by default when using cargo build or cargo run without the --release flag, as we have here.

In the output in Listing 9-2, line 6 of the backtrace points to the line in our project that’s causing the problem: line 4 of src/main.rs. If we don’t want our program to panic, we should start our investigation at the location pointed to by the first line mentioning a file we wrote. In Listing 9-1, where we deliberately wrote code that would panic, the way to fix the panic is to not request an element beyond the range of the vector indexes. When your code panics in the future, you’ll need to figure out what action the code is taking with what values to cause the panic and what the code should do instead.

We’ll come back to panic! and when we should and should not use panic! to handle error conditions in the “To panic! or Not to panic! section later in this chapter. Next, we’ll look at how to recover from an error using Result.

Recoverable Errors with Result

Most errors aren’t serious enough to require the program to stop entirely. Sometimes, when a function fails, it’s for a reason that you can easily interpret and respond to. For example, if you try to open a file and that operation fails because the file doesn’t exist, you might want to create the file instead of terminating the process.

Recall from “Handling Potential Failure with Result in Chapter 2 that the Result enum is defined as having two variants, Ok and Err, as follows:

#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),
    Err(E),
}
}

The T and E are generic type parameters: we’ll discuss generics in more detail in Chapter 10. What you need to know right now is that T represents the type of the value that will be returned in a success case within the Ok variant, and E represents the type of the error that will be returned in a failure case within the Err variant. Because Result has these generic type parameters, we can use the Result type and the functions defined on it in many different situations where the successful value and error value we want to return may differ.

Let’s call a function that returns a Result value because the function could fail. In Listing 9-3 we try to open a file.

Filename: src/main.rs

use std::fs::File;

fn main() {
    let greeting_file_result = File::open("hello.txt");
}

Listing 9-3: Opening a file

The return type of File::open is a Result<T, E>. The generic parameter T has been filled in by the implementation of File::open with the type of the success value, std::fs::File, which is a file handle. The type of E used in the error value is std::io::Error. This return type means the call to File::open might succeed and return a file handle that we can read from or write to. The function call also might fail: for example, the file might not exist, or we might not have permission to access the file. The File::open function needs to have a way to tell us whether it succeeded or failed and at the same time give us either the file handle or error information. This information is exactly what the Result enum conveys.

In the case where File::open succeeds, the value in the variable greeting_file_result will be an instance of Ok that contains a file handle. In the case where it fails, the value in greeting_file_result will be an instance of Err that contains more information about the kind of error that happened.

We need to add to the code in Listing 9-3 to take different actions depending on the value File::open returns. Listing 9-4 shows one way to handle the Result using a basic tool, the match expression that we discussed in Chapter 6.

Filename: 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),
    };
}

Listing 9-4: Using a match expression to handle the Result variants that might be returned

Note that, like the Option enum, the Result enum and its variants have been brought into scope by the prelude, so we don’t need to specify Result:: before the Ok and Err variants in the match arms.

When the result is Ok, this code will return the inner file value out of the Ok variant, and we then assign that file handle value to the variable greeting_file. After the match, we can use the file handle for reading or writing.

The other arm of the match handles the case where we get an Err value from File::open. In this example, we’ve chosen to call the panic! macro. If there’s no file named hello.txt in our current directory and we run this code, we’ll see the following output from the panic! macro:

$ 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

As usual, this output tells us exactly what has gone wrong.

Matching on Different Errors

The code in Listing 9-4 will panic! no matter why File::open failed. However, we want to take different actions for different failure reasons: if File::open failed because the file doesn’t exist, we want to create the file and return the handle to the new file. If File::open failed for any other reason—for example, because we didn’t have permission to open the file—we still want the code to panic! in the same way as it did in Listing 9-4. For this we add an inner match expression, shown in Listing 9-5.

Filename: 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);
            }
        },
    };
}

Listing 9-5: Handling different kinds of errors in different ways

The type of the value that File::open returns inside the Err variant is io::Error, which is a struct provided by the standard library. This struct has a method kind that we can call to get an io::ErrorKind value. The enum io::ErrorKind is provided by the standard library and has variants representing the different kinds of errors that might result from an io operation. The variant we want to use is ErrorKind::NotFound, which indicates the file we’re trying to open doesn’t exist yet. So we match on greeting_file_result, but we also have an inner match on error.kind().

The condition we want to check in the inner match is whether the value returned by error.kind() is the NotFound variant of the ErrorKind enum. If it is, we try to create the file with File::create. However, because File::create could also fail, we need a second arm in the inner match expression. When the file can’t be created, a different error message is printed. The second arm of the outer match stays the same, so the program panics on any error besides the missing file error.

Alternatives to Using match with Result<T, E>

That’s a lot of match! The match expression is very useful but also very much a primitive. In Chapter 13, you’ll learn about closures, which are used with many of the methods defined on Result<T, E>. These methods can be more concise than using match when handling Result<T, E> values in your code.

For example, here’s another way to write the same logic as shown in Listing 9-5, this time using closures and the unwrap_or_else method:

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);
        }
    });
}

Although this code has the same behavior as Listing 9-5, it doesn’t contain any match expressions and is cleaner to read. Come back to this example after you’ve read Chapter 13, and look up the unwrap_or_else method in the standard library documentation. Many more of these methods can clean up huge nested match expressions when you’re dealing with errors.

Shortcuts for Panic on Error: unwrap and expect

Using match works well enough, but it can be a bit verbose and doesn’t always communicate intent well. The Result<T, E> type has many helper methods defined on it to do various, more specific tasks. The unwrap method is a shortcut method implemented just like the match expression we wrote in Listing 9-4. If the Result value is the Ok variant, unwrap will return the value inside the Ok. If the Result is the Err variant, unwrap will call the panic! macro for us. Here is an example of unwrap in action:

Filename: src/main.rs

use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt").unwrap();
}

If we run this code without a hello.txt file, we’ll see an error message from the panic! call that the unwrap method makes:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:4:49

Similarly, the expect method lets us also choose the panic! error message. Using expect instead of unwrap and providing good error messages can convey your intent and make tracking down the source of a panic easier. The syntax of expect looks like this:

Filename: 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");
}

We use expect in the same way as unwrap: to return the file handle or call the panic! macro. The error message used by expect in its call to panic! will be the parameter that we pass to expect, rather than the default panic! message that unwrap uses. Here’s what it looks like:

thread 'main' panicked at 'hello.txt should be included in this project: Os {
code: 2, kind: NotFound, message: "No such file or directory" }',
src/main.rs:5:10

In production-quality code, most Rustaceans choose expect rather than unwrap and give more context about why the operation is expected to always succeed. That way, if your assumptions are ever proven wrong, you have more information to use in debugging.

Propagating Errors

When a function’s implementation calls something that might fail, instead of handling the error within the function itself, you can return the error to the calling code so that it can decide what to do. This is known as propagating the error and gives more control to the calling code, where there might be more information or logic that dictates how the error should be handled than what you have available in the context of your code.

For example, Listing 9-6 shows a function that reads a username from a file. If the file doesn’t exist or can’t be read, this function will return those errors to the code that called the function.

Filename: 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),
    }
}
}

Listing 9-6: A function that returns errors to the calling code using match

This function can be written in a much shorter way, but we’re going to start by doing a lot of it manually in order to explore error handling; at the end, we’ll show the shorter way. Let’s look at the return type of the function first: Result<String, io::Error>. This means the function is returning a value of the type Result<T, E> where the generic parameter T has been filled in with the concrete type String, and the generic type E has been filled in with the concrete type io::Error.

If this function succeeds without any problems, the code that calls this function will receive an Ok value that holds a String—the username that this function read from the file. If this function encounters any problems, the calling code will receive an Err value that holds an instance of io::Error that contains more information about what the problems were. We chose io::Error as the return type of this function because that happens to be the type of the error value returned from both of the operations we’re calling in this function’s body that might fail: the File::open function and the read_to_string method.

The body of the function starts by calling the File::open function. Then we handle the Result value with a match similar to the match in Listing 9-4. If File::open succeeds, the file handle in the pattern variable file becomes the value in the mutable variable username_file and the function continues. In the Err case, instead of calling panic!, we use the return keyword to return early out of the function entirely and pass the error value from File::open, now in the pattern variable e, back to the calling code as this function’s error value.

So if we have a file handle in username_file, the function then creates a new String in variable username and calls the read_to_string method on the file handle in username_file to read the contents of the file into username. The read_to_string method also returns a Result because it might fail, even though File::open succeeded. So we need another match to handle that Result: if read_to_string succeeds, then our function has succeeded, and we return the username from the file that’s now in username wrapped in an Ok. If read_to_string fails, we return the error value in the same way that we returned the error value in the match that handled the return value of File::open. However, we don’t need to explicitly say return, because this is the last expression in the function.

The code that calls this code will then handle getting either an Ok value that contains a username or an Err value that contains an io::Error. It’s up to the calling code to decide what to do with those values. If the calling code gets an Err value, it could call panic! and crash the program, use a default username, or look up the username from somewhere other than a file, for example. We don’t have enough information on what the calling code is actually trying to do, so we propagate all the success or error information upward for it to handle appropriately.

This pattern of propagating errors is so common in Rust that Rust provides the question mark operator ? to make this easier.

A Shortcut for Propagating Errors: the ? Operator

Listing 9-7 shows an implementation of read_username_from_file that has the same functionality as in Listing 9-6, but this implementation uses the ? operator.

Filename: 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)
}
}

Listing 9-7: A function that returns errors to the calling code using the ? operator

The ? placed after a Result value is defined to work in almost the same way as the match expressions we defined to handle the Result values in Listing 9-6. If the value of the Result is an Ok, the value inside the Ok will get returned from this expression, and the program will continue. If the value is an Err, the Err will be returned from the whole function as if we had used the return keyword so the error value gets propagated to the calling code.

There is a difference between what the match expression from Listing 9-6 does and what the ? operator does: error values that have the ? operator called on them go through the from function, defined in the From trait in the standard library, which is used to convert values from one type into another. When the ? operator calls the from function, the error type received is converted into the error type defined in the return type of the current function. This is useful when a function returns one error type to represent all the ways a function might fail, even if parts might fail for many different reasons.

For example, we could change the read_username_from_file function in Listing 9-7 to return a custom error type named OurError that we define. If we also define impl From<io::Error> for OurError to construct an instance of OurError from an io::Error, then the ? operator calls in the body of read_username_from_file will call from and convert the error types without needing to add any more code to the function.

In the context of Listing 9-7, the ? at the end of the File::open call will return the value inside an Ok to the variable username_file. If an error occurs, the ? operator will return early out of the whole function and give any Err value to the calling code. The same thing applies to the ? at the end of the read_to_string call.

The ? operator eliminates a lot of boilerplate and makes this function’s implementation simpler. We could even shorten this code further by chaining method calls immediately after the ?, as shown in Listing 9-8.

Filename: 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)
}
}

Listing 9-8: Chaining method calls after the ? operator

We’ve moved the creation of the new String in username to the beginning of the function; that part hasn’t changed. Instead of creating a variable username_file, we’ve chained the call to read_to_string directly onto the result of File::open("hello.txt")?. We still have a ? at the end of the read_to_string call, and we still return an Ok value containing username when both File::open and read_to_string succeed rather than returning errors. The functionality is again the same as in Listing 9-6 and Listing 9-7; this is just a different, more ergonomic way to write it.

Listing 9-9 shows a way to make this even shorter using fs::read_to_string.

Filename: 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")
}
}

Listing 9-9: Using fs::read_to_string instead of opening and then reading the file

Reading a file into a string is a fairly common operation, so the standard library provides the convenient fs::read_to_string function that opens the file, creates a new String, reads the contents of the file, puts the contents into that String, and returns it. Of course, using fs::read_to_string doesn’t give us the opportunity to explain all the error handling, so we did it the longer way first.

Where The ? Operator Can Be Used

The ? operator can only be used in functions whose return type is compatible with the value the ? is used on. This is because the ? operator is defined to perform an early return of a value out of the function, in the same manner as the match expression we defined in Listing 9-6. In Listing 9-6, the match was using a Result value, and the early return arm returned an Err(e) value. The return type of the function has to be a Result so that it’s compatible with this return.

In Listing 9-10, let’s look at the error we’ll get if we use the ? operator in a main function with a return type incompatible with the type of the value we use ? on:

Filename: src/main.rs

use std::fs::File;

fn main() {
    let greeting_file = File::open("hello.txt")?;
}

Listing 9-10: Attempting to use the ? in the main function that returns () won’t compile

This code opens a file, which might fail. The ? operator follows the Result value returned by File::open, but this main function has the return type of (), not Result. When we compile this code, we get the following error message:

$ 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

This error points out that we’re only allowed to use the ? operator in a function that returns Result, Option, or another type that implements FromResidual.

To fix the error, you have two choices. One choice is to change the return type of your function to be compatible with the value you’re using the ? operator on as long as you have no restrictions preventing that. The other technique is to use a match or one of the Result<T, E> methods to handle the Result<T, E> in whatever way is appropriate.

The error message also mentioned that ? can be used with Option<T> values as well. As with using ? on Result, you can only use ? on Option in a function that returns an Option. The behavior of the ? operator when called on an Option<T> is similar to its behavior when called on a Result<T, E>: if the value is None, the None will be returned early from the function at that point. If the value is Some, the value inside the Some is the resulting value of the expression and the function continues. Listing 9-11 has an example of a function that finds the last character of the first line in the given text:

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);
}

Listing 9-11: Using the ? operator on an Option<T> value

This function returns Option<char> because it’s possible that there is a character there, but it’s also possible that there isn’t. This code takes the text string slice argument and calls the lines method on it, which returns an iterator over the lines in the string. Because this function wants to examine the first line, it calls next on the iterator to get the first value from the iterator. If text is the empty string, this call to next will return None, in which case we use ? to stop and return None from last_char_of_first_line. If text is not the empty string, next will return a Some value containing a string slice of the first line in text.

The ? extracts the string slice, and we can call chars on that string slice to get an iterator of its characters. We’re interested in the last character in this first line, so we call last to return the last item in the iterator. This is an Option because it’s possible that the first line is the empty string, for example if text starts with a blank line but has characters on other lines, as in "\nhi". However, if there is a last character on the first line, it will be returned in the Some variant. The ? operator in the middle gives us a concise way to express this logic, allowing us to implement the function in one line. If we couldn’t use the ? operator on Option, we’d have to implement this logic using more method calls or a match expression.

Note that you can use the ? operator on a Result in a function that returns Result, and you can use the ? operator on an Option in a function that returns Option, but you can’t mix and match. The ? operator won’t automatically convert a Result to an Option or vice versa; in those cases, you can use methods like the ok method on Result or the ok_or method on Option to do the conversion explicitly.

So far, all the main functions we’ve used return (). The main function is special because it’s the entry and exit point of executable programs, and there are restrictions on what its return type can be for the programs to behave as expected.

Luckily, main can also return a Result<(), E>. Listing 9-12 has the code from Listing 9-10 but we’ve changed the return type of main to be Result<(), Box<dyn Error>> and added a return value Ok(()) to the end. This code will now compile:

use std::error::Error;
use std::fs::File;

fn main() -> Result<(), Box<dyn Error>> {
    let greeting_file = File::open("hello.txt")?;

    Ok(())
}

Listing 9-12: Changing main to return Result<(), E> allows the use of the ? operator on Result values

The Box<dyn Error> type is a trait object, which we’ll talk about in the “Using Trait Objects that Allow for Values of Different Types” section in Chapter 17. For now, you can read Box<dyn Error> to mean “any kind of error.” Using ? on a Result value in a main function with the error type Box<dyn Error> is allowed, because it allows any Err value to be returned early. Even though the body of this main function will only ever return errors of type std::io::Error, by specifying Box<dyn Error>, this signature will continue to be correct even if more code that returns other errors is added to the body of main.

When a main function returns a Result<(), E>, the executable will exit with a value of 0 if main returns Ok(()) and will exit with a nonzero value if main returns an Err value. Executables written in C return integers when they exit: programs that exit successfully return the integer 0, and programs that error return some integer other than 0. Rust also returns integers from executables to be compatible with this convention.

The main function may return any types that implement the std::process::Termination trait, which contains a function report that returns an ExitCode. Consult the standard library documentation for more information on implementing the Termination trait for your own types.

Now that we’ve discussed the details of calling panic! or returning Result, let’s return to the topic of how to decide which is appropriate to use in which cases.

To panic! or Not to panic!

So how do you decide when you should call panic! and when you should return Result? When code panics, there’s no way to recover. You could call panic! for any error situation, whether there’s a possible way to recover or not, but then you’re making the decision that a situation is unrecoverable on behalf of the calling code. When you choose to return a Result value, you give the calling code options. The calling code could choose to attempt to recover in a way that’s appropriate for its situation, or it could decide that an Err value in this case is unrecoverable, so it can call panic! and turn your recoverable error into an unrecoverable one. Therefore, returning Result is a good default choice when you’re defining a function that might fail.

In situations such as examples, prototype code, and tests, it’s more appropriate to write code that panics instead of returning a Result. Let’s explore why, then discuss situations in which the compiler can’t tell that failure is impossible, but you as a human can. The chapter will conclude with some general guidelines on how to decide whether to panic in library code.

Examples, Prototype Code, and Tests

When you’re writing an example to illustrate some concept, also including robust error-handling code can make the example less clear. In examples, it’s understood that a call to a method like unwrap that could panic is meant as a placeholder for the way you’d want your application to handle errors, which can differ based on what the rest of your code is doing.

Similarly, the unwrap and expect methods are very handy when prototyping, before you’re ready to decide how to handle errors. They leave clear markers in your code for when you’re ready to make your program more robust.

If a method call fails in a test, you’d want the whole test to fail, even if that method isn’t the functionality under test. Because panic! is how a test is marked as a failure, calling unwrap or expect is exactly what should happen.

Cases in Which You Have More Information Than the Compiler

It would also be appropriate to call unwrap or expect when you have some other logic that ensures the Result will have an Ok value, but the logic isn’t something the compiler understands. You’ll still have a Result value that you need to handle: whatever operation you’re calling still has the possibility of failing in general, even though it’s logically impossible in your particular situation. If you can ensure by manually inspecting the code that you’ll never have an Err variant, it’s perfectly acceptable to call unwrap, and even better to document the reason you think you’ll never have an Err variant in the expect text. Here’s an example:

fn main() {
    use std::net::IpAddr;

    let home: IpAddr = "127.0.0.1"
        .parse()
        .expect("Hardcoded IP address should be valid");
}

We’re creating an IpAddr instance by parsing a hardcoded string. We can see that 127.0.0.1 is a valid IP address, so it’s acceptable to use expect here. However, having a hardcoded, valid string doesn’t change the return type of the parse method: we still get a Result value, and the compiler will still make us handle the Result as if the Err variant is a possibility because the compiler isn’t smart enough to see that this string is always a valid IP address. If the IP address string came from a user rather than being hardcoded into the program and therefore did have a possibility of failure, we’d definitely want to handle the Result in a more robust way instead. Mentioning the assumption that this IP address is hardcoded will prompt us to change expect to better error handling code if in the future, we need to get the IP address from some other source instead.

Guidelines for Error Handling

It’s advisable to have your code panic when it’s possible that your code could end up in a bad state. In this context, a bad state is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to your code—plus one or more of the following:

  • The bad state is something that is unexpected, as opposed to something that will likely happen occasionally, like a user entering data in the wrong format.
  • Your code after this point needs to rely on not being in this bad state, rather than checking for the problem at every step.
  • There’s not a good way to encode this information in the types you use. We’ll work through an example of what we mean in the “Encoding States and Behavior as Types” section of Chapter 17.

If someone calls your code and passes in values that don’t make sense, it’s best to return an error if you can so the user of the library can decide what they want to do in that case. However, in cases where continuing could be insecure or harmful, the best choice might be to call panic! and alert the person using your library to the bug in their code so they can fix it during development. Similarly, panic! is often appropriate if you’re calling external code that is out of your control and it returns an invalid state that you have no way of fixing.

However, when failure is expected, it’s more appropriate to return a Result than to make a panic! call. Examples include a parser being given malformed data or an HTTP request returning a status that indicates you have hit a rate limit. In these cases, returning a Result indicates that failure is an expected possibility that the calling code must decide how to handle.

When your code performs an operation that could put a user at risk if it’s called using invalid values, your code should verify the values are valid first and panic if the values aren’t valid. This is mostly for safety reasons: attempting to operate on invalid data can expose your code to vulnerabilities. This is the main reason the standard library will call panic! if you attempt an out-of-bounds memory access: trying to access memory that doesn’t belong to the current data structure is a common security problem. Functions often have contracts: their behavior is only guaranteed if the inputs meet particular requirements. Panicking when the contract is violated makes sense because a contract violation always indicates a caller-side bug and it’s not a kind of error you want the calling code to have to explicitly handle. In fact, there’s no reasonable way for calling code to recover; the calling programmers need to fix the code. Contracts for a function, especially when a violation will cause a panic, should be explained in the API documentation for the function.

However, having lots of error checks in all of your functions would be verbose and annoying. Fortunately, you can use Rust’s type system (and thus the type checking done by the compiler) to do many of the checks for you. If your function has a particular type as a parameter, you can proceed with your code’s logic knowing that the compiler has already ensured you have a valid value. For example, if you have a type rather than an Option, your program expects to have something rather than nothing. Your code then doesn’t have to handle two cases for the Some and None variants: it will only have one case for definitely having a value. Code trying to pass nothing to your function won’t even compile, so your function doesn’t have to check for that case at runtime. Another example is using an unsigned integer type such as u32, which ensures the parameter is never negative.

Creating Custom Types for Validation

Let’s take the idea of using Rust’s type system to ensure we have a valid value one step further and look at creating a custom type for validation. Recall the guessing game in Chapter 2 in which our code asked the user to guess a number between 1 and 100. We never validated that the user’s guess was between those numbers before checking it against our secret number; we only validated that the guess was positive. In this case, the consequences were not very dire: our output of “Too high” or “Too low” would still be correct. But it would be a useful enhancement to guide the user toward valid guesses and have different behavior when a user guesses a number that’s out of range versus when a user types, for example, letters instead.

One way to do this would be to parse the guess as an i32 instead of only a u32 to allow potentially negative numbers, and then add a check for the number being in range, like so:

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;
            }
        }
    }
}

The if expression checks whether our value is out of range, tells the user about the problem, and calls continue to start the next iteration of the loop and ask for another guess. After the if expression, we can proceed with the comparisons between guess and the secret number knowing that guess is between 1 and 100.

However, this is not an ideal solution: if it was absolutely critical that the program only operated on values between 1 and 100, and it had many functions with this requirement, having a check like this in every function would be tedious (and might impact performance).

Instead, we can make a new type and put the validations in a function to create an instance of the type rather than repeating the validations everywhere. That way, it’s safe for functions to use the new type in their signatures and confidently use the values they receive. Listing 9-13 shows one way to define a Guess type that will only create an instance of Guess if the new function receives a value between 1 and 100.

#![allow(unused)]
fn main() {
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 }
    }

    pub fn value(&self) -> i32 {
        self.value
    }
}
}

Listing 9-13: A Guess type that will only continue with values between 1 and 100

First, we define a struct named Guess that has a field named value that holds an i32. This is where the number will be stored.

Then we implement an associated function named new on Guess that creates instances of Guess values. The new function is defined to have one parameter named value of type i32 and to return a Guess. The code in the body of the new function tests value to make sure it’s between 1 and 100. If value doesn’t pass this test, we make a panic! call, which will alert the programmer who is writing the calling code that they have a bug they need to fix, because creating a Guess with a value outside this range would violate the contract that Guess::new is relying on. The conditions in which Guess::new might panic should be discussed in its public-facing API documentation; we’ll cover documentation conventions indicating the possibility of a panic! in the API documentation that you create in Chapter 14. If value does pass the test, we create a new Guess with its value field set to the value parameter and return the Guess.

Next, we implement a method named value that borrows self, doesn’t have any other parameters, and returns an i32. This kind of method is sometimes called a getter, because its purpose is to get some data from its fields and return it. This public method is necessary because the value field of the Guess struct is private. It’s important that the value field be private so code using the Guess struct is not allowed to set value directly: code outside the module must use the Guess::new function to create an instance of Guess, thereby ensuring there’s no way for a Guess to have a value that hasn’t been checked by the conditions in the Guess::new function.

A function that has a parameter or returns only numbers between 1 and 100 could then declare in its signature that it takes or returns a Guess rather than an i32 and wouldn’t need to do any additional checks in its body.

Summary

Rust’s error handling features are designed to help you write more robust code. The panic! macro signals that your program is in a state it can’t handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The Result enum uses Rust’s type system to indicate that operations might fail in a way that your code could recover from. You can use Result to tell code that calls your code that it needs to handle potential success or failure as well. Using panic! and Result in the appropriate situations will make your code more reliable in the face of inevitable problems.

Now that you’ve seen useful ways that the standard library uses generics with the Option and Result enums, we’ll talk about how generics work and how you can use them in your code.

Generic Types, Traits, and Lifetimes

Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is generics: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code.

Functions can take parameters of some generic type, instead of a concrete type like i32 or String, in the same way a function takes parameters with unknown values to run the same code on multiple concrete values. In fact, we’ve already used generics in Chapter 6 with Option<T>, Chapter 8 with Vec<T> and HashMap<K, V>, and Chapter 9 with Result<T, E>. In this chapter, you’ll explore how to define your own types, functions, and methods with generics!

First, we’ll review how to extract a function to reduce code duplication. We’ll then use the same technique to make a generic function from two functions that differ only in the types of their parameters. We’ll also explain how to use generic types in struct and enum definitions.

Then you’ll learn how to use traits to define behavior in a generic way. You can combine traits with generic types to constrain a generic type to accept only those types that have a particular behavior, as opposed to just any type.

Finally, we’ll discuss lifetimes: a variety of generics that give the compiler information about how references relate to each other. Lifetimes allow us to give the compiler enough information about borrowed values so that it can ensure references will be valid in more situations than it could without our help.

Removing Duplication by Extracting a Function

Generics allow us to replace specific types with a placeholder that represents multiple types to remove code duplication. Before diving into generics syntax, then, let’s first look at how to remove duplication in a way that doesn’t involve generic types by extracting a function that replaces specific values with a placeholder that represents multiple values. Then we’ll apply the same technique to extract a generic function! By looking at how to recognize duplicated code you can extract into a function, you’ll start to recognize duplicated code that can use generics.

We begin with the short program in Listing 10-1 that finds the largest number in a list.

Filename: 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);
}

Listing 10-1: Finding the largest number in a list of numbers

We store a list of integers in the variable number_list and place a reference to the first number in the list in a variable named largest. We then iterate through all the numbers in the list, and if the current number is greater than the number stored in largest, replace the reference in that variable. However, if the current number is less than or equal to the largest number seen so far, the variable doesn’t change, and the code moves on to the next number in the list. After considering all the numbers in the list, largest should refer to the largest number, which in this case is 100.

We've now been tasked with finding the largest number in two different lists of numbers. To do so, we can choose to duplicate the code in Listing 10-1 and use the same logic at two different places in the program, as shown in Listing 10-2.

Filename: 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);
}

Listing 10-2: Code to find the largest number in two lists of numbers

Although this code works, duplicating code is tedious and error prone. We also have to remember to update the code in multiple places when we want to change it.

To eliminate this duplication, we’ll create an abstraction by defining a function that operates on any list of integers passed in a parameter. This solution makes our code clearer and lets us express the concept of finding the largest number in a list abstractly.

In Listing 10-3, we extract the code that finds the largest number into a function named largest. Then we call the function to find the largest number in the two lists from Listing 10-2. We could also use the function on any other list of i32 values we might have in the future.

Filename: 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);
}

Listing 10-3: Abstracted code to find the largest number in two lists

The largest function has a parameter called list, which represents any concrete slice of i32 values we might pass into the function. As a result, when we call the function, the code runs on the specific values that we pass in.

In summary, here are the steps we took to change the code from Listing 10-2 to Listing 10-3:

  1. Identify duplicate code.
  2. Extract the duplicate code into the body of the function and specify the inputs and return values of that code in the function signature.
  3. Update the two instances of duplicated code to call the function instead.

Next, we’ll use these same steps with generics to reduce code duplication. In the same way that the function body can operate on an abstract list instead of specific values, generics allow code to operate on abstract types.

For example, say we had two functions: one that finds the largest item in a slice of i32 values and one that finds the largest item in a slice of char values. How would we eliminate that duplication? Let’s find out!

Generic Data Types

We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let’s first look at how to define functions, structs, enums, and methods using generics. Then we’ll discuss how generics affect code performance.

In Function Definitions

When defining a function that uses generics, we place the generics in the signature of the function where we would usually specify the data types of the parameters and return value. Doing so makes our code more flexible and provides more functionality to callers of our function while preventing code duplication.

Continuing with our largest function, Listing 10-4 shows two functions that both find the largest value in a slice. We'll then combine these into a single function that uses generics.

Filename: 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');
}

Listing 10-4: Two functions that differ only in their names and the types in their signatures

The largest_i32 function is the one we extracted in Listing 10-3 that finds the largest i32 in a slice. The largest_char function finds the largest char in a slice. The function bodies have the same code, so let’s eliminate the duplication by introducing a generic type parameter in a single function.

To parameterize the types in a new single function, we need to name the type parameter, just as we do for the value parameters to a function. You can use any identifier as a type parameter name. But we’ll use T because, by convention, type parameter names in Rust are short, often just a letter, and Rust’s type-naming convention is UpperCamelCase. Short for “type,” T is the default choice of most Rust programmers.

When we use a parameter in the body of the function, we have to declare the parameter name in the signature so the compiler knows what that name means. Similarly, when we use a type parameter name in a function signature, we have to declare the type parameter name before we use it. To define the generic largest function, place type name declarations inside angle brackets, <>, between the name of the function and the parameter list, like this:

fn largest<T>(list: &[T]) -> &T {

We read this definition as: the function largest is generic over some type T. This function has one parameter named list, which is a slice of values of type T. The largest function will return a reference to a value of the same type T.

Listing 10-5 shows the combined largest function definition using the generic data type in its signature. The listing also shows how we can call the function with either a slice of i32 values or char values. Note that this code won’t compile yet, but we’ll fix it later in this chapter.

Filename: 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);
}

Listing 10-5: The largest function using generic type parameters; this doesn’t yet compile

If we compile this code right now, we’ll get this error:

$ 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

The help text mentions std::cmp::PartialOrd, which is a trait, and we’re going to talk about traits in the next section. For now, know that this error states that the body of largest won’t work for all possible types that T could be. Because we want to compare values of type T in the body, we can only use types whose values can be ordered. To enable comparisons, the standard library has the std::cmp::PartialOrd trait that you can implement on types (see Appendix C for more on this trait). By following the help text's suggestion, we restrict the types valid for T to only those that implement PartialOrd and this example will compile, because the standard library implements PartialOrd on both i32 and char.

In Struct Definitions

We can also define structs to use a generic type parameter in one or more fields using the <> syntax. Listing 10-6 defines a Point<T> struct to hold x and y coordinate values of any type.

Filename: 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 };
}

Listing 10-6: A Point<T> struct that holds x and y values of type T

The syntax for using generics in struct definitions is similar to that used in function definitions. First, we declare the name of the type parameter inside angle brackets just after the name of the struct. Then we use the generic type in the struct definition where we would otherwise specify concrete data types.

Note that because we’ve used only one generic type to define Point<T>, this definition says that the Point<T> struct is generic over some type T, and the fields x and y are both that same type, whatever that type may be. If we create an instance of a Point<T> that has values of different types, as in Listing 10-7, our code won’t compile.

Filename: src/main.rs

struct Point<T> {
    x: T,
    y: T,
}

fn main() {
    let wont_work = Point { x: 5, y: 4.0 };
}

Listing 10-7: The fields x and y must be the same type because both have the same generic data type T.

In this example, when we assign the integer value 5 to x, we let the compiler know that the generic type T will be an integer for this instance of Point<T>. Then when we specify 4.0 for y, which we’ve defined to have the same type as x, we’ll get a type mismatch error like this:

$ 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

To define a Point struct where x and y are both generics but could have different types, we can use multiple generic type parameters. For example, in Listing 10-8, we change the definition of Point to be generic over types T and U where x is of type T and y is of type U.

Filename: 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 };
}

Listing 10-8: A Point<T, U> generic over two types so that x and y can be values of different types

Now all the instances of Point shown are allowed! You can use as many generic type parameters in a definition as you want, but using more than a few makes your code hard to read. If you're finding you need lots of generic types in your code, it could indicate that your code needs restructuring into smaller pieces.

In Enum Definitions

As we did with structs, we can define enums to hold generic data types in their variants. Let’s take another look at the Option<T> enum that the standard library provides, which we used in Chapter 6:

#![allow(unused)]
fn main() {
enum Option<T> {
    Some(T),
    None,
}
}

This definition should now make more sense to you. As you can see, the Option<T> enum is generic over type T and has two variants: Some, which holds one value of type T, and a None variant that doesn’t hold any value. By using the Option<T> enum, we can express the abstract concept of an optional value, and because Option<T> is generic, we can use this abstraction no matter what the type of the optional value is.

Enums can use multiple generic types as well. The definition of the Result enum that we used in Chapter 9 is one example:

#![allow(unused)]
fn main() {
enum Result<T, E> {
    Ok(T),
    Err(E),
}
}

The Result enum is generic over two types, T and E, and has two variants: Ok, which holds a value of type T, and Err, which holds a value of type E. This definition makes it convenient to use the Result enum anywhere we have an operation that might succeed (return a value of some type T) or fail (return an error of some type E). In fact, this is what we used to open a file in Listing 9-3, where T was filled in with the type std::fs::File when the file was opened successfully and E was filled in with the type std::io::Error when there were problems opening the file.

When you recognize situations in your code with multiple struct or enum definitions that differ only in the types of the values they hold, you can avoid duplication by using generic types instead.

In Method Definitions

We can implement methods on structs and enums (as we did in Chapter 5) and use generic types in their definitions, too. Listing 10-9 shows the Point<T> struct we defined in Listing 10-6 with a method named x implemented on it.

Filename: 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());
}

Listing 10-9: Implementing a method named x on the Point<T> struct that will return a reference to the x field of type T

Here, we’ve defined a method named x on Point<T> that returns a reference to the data in the field x.

Note that we have to declare T just after impl so we can use T to specify that we’re implementing methods on the type Point<T>. By declaring T as a generic type after impl, Rust can identify that the type in the angle brackets in Point is a generic type rather than a concrete type. We could have chosen a different name for this generic parameter than the generic parameter declared in the struct definition, but using the same name is conventional. Methods written within an impl that declares the generic type will be defined on any instance of the type, no matter what concrete type ends up substituting for the generic type.

We can also specify constraints on generic types when defining methods on the type. We could, for example, implement methods only on Point<f32> instances rather than on Point<T> instances with any generic type. In Listing 10-10 we use the concrete type f32, meaning we don’t declare any types after impl.

Filename: 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());
}

Listing 10-10: An impl block that only applies to a struct with a particular concrete type for the generic type parameter T

This code means the type Point<f32> will have a distance_from_origin method; other instances of Point<T> where T is not of type f32 will not have this method defined. The method measures how far our point is from the point at coordinates (0.0, 0.0) and uses mathematical operations that are available only for floating point types.

Generic type parameters in a struct definition aren’t always the same as those you use in that same struct’s method signatures. Listing 10-11 uses the generic types X1 and Y1 for the Point struct and X2 Y2 for the mixup method signature to make the example clearer. The method creates a new Point instance with the x value from the self Point (of type X1) and the y value from the passed-in Point (of type Y2).

Filename: 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);
}

Listing 10-11: A method that uses generic types different from its struct’s definition

In main, we’ve defined a Point that has an i32 for x (with value 5) and an f64 for y (with value 10.4). The p2 variable is a Point struct that has a string slice for x (with value "Hello") and a char for y (with value c). Calling mixup on p1 with the argument p2 gives us p3, which will have an i32 for x, because x came from p1. The p3 variable will have a char for y, because y came from p2. The println! macro call will print p3.x = 5, p3.y = c.

The purpose of this example is to demonstrate a situation in which some generic parameters are declared with impl and some are declared with the method definition. Here, the generic parameters X1 and Y1 are declared after impl because they go with the struct definition. The generic parameters X2 and Y2 are declared after fn mixup, because they’re only relevant to the method.

Performance of Code Using Generics

You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types.

Rust accomplishes this by performing monomorphization of the code using generics at compile time. Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. In this process, the compiler does the opposite of the steps we used to create the generic function in Listing 10-5: the compiler looks at all the places where generic code is called and generates code for the concrete types the generic code is called with.

Let’s look at how this works by using the standard library’s generic Option<T> enum:

#![allow(unused)]
fn main() {
let integer = Some(5);
let float = Some(5.0);
}

When Rust compiles this code, it performs monomorphization. During that process, the compiler reads the values that have been used in Option<T> instances and identifies two kinds of Option<T>: one is i32 and the other is f64. As such, it expands the generic definition of Option<T> into two definitions specialized to i32 and f64, thereby replacing the generic definition with the specific ones.

The monomorphized version of the code looks similar to the following (the compiler uses different names than what we’re using here for illustration):

Filename: 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);
}

The generic Option<T> is replaced with the specific definitions created by the compiler. Because Rust compiles generic code into code that specifies the type in each instance, we pay no runtime cost for using generics. When the code runs, it performs just as it would if we had duplicated each definition by hand. The process of monomorphization makes Rust’s generics extremely efficient at runtime.

Traits: Defining Shared Behavior

A trait defines functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way. We can use trait bounds to specify that a generic type can be any type that has certain behavior.

Note: Traits are similar to a feature often called interfaces in other languages, although with some differences.

Defining a Trait

A type’s behavior consists of the methods we can call on that type. Different types share the same behavior if we can call the same methods on all of those types. Trait definitions are a way to group method signatures together to define a set of behaviors necessary to accomplish some purpose.

For example, let’s say we have multiple structs that hold various kinds and amounts of text: a NewsArticle struct that holds a news story filed in a particular location and a Tweet that can have at most 280 characters along with metadata that indicates whether it was a new tweet, a retweet, or a reply to another tweet.

We want to make a media aggregator library crate named aggregator that can display summaries of data that might be stored in a NewsArticle or Tweet instance. To do this, we need a summary from each type, and we’ll request that summary by calling a summarize method on an instance. Listing 10-12 shows the definition of a public Summary trait that expresses this behavior.

Filename: src/lib.rs

pub trait Summary {
    fn summarize(&self) -> String;
}

Listing 10-12: A Summary trait that consists of the behavior provided by a summarize method

Here, we declare a trait using the trait keyword and then the trait’s name, which is Summary in this case. We’ve also declared the trait as pub so that crates depending on this crate can make use of this trait too, as we’ll see in a few examples. Inside the curly brackets, we declare the method signatures that describe the behaviors of the types that implement this trait, which in this case is fn summarize(&self) -> String.

After the method signature, instead of providing an implementation within curly brackets, we use a semicolon. Each type implementing this trait must provide its own custom behavior for the body of the method. The compiler will enforce that any type that has the Summary trait will have the method summarize defined with this signature exactly.

A trait can have multiple methods in its body: the method signatures are listed one per line and each line ends in a semicolon.

Implementing a Trait on a Type

Now that we’ve defined the desired signatures of the Summary trait’s methods, we can implement it on the types in our media aggregator. Listing 10-13 shows an implementation of the Summary trait on the NewsArticle struct that uses the headline, the author, and the location to create the return value of summarize. For the Tweet struct, we define summarize as the username followed by the entire text of the tweet, assuming that tweet content is already limited to 280 characters.

Filename: 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)
    }
}

Listing 10-13: Implementing the Summary trait on the NewsArticle and Tweet types

Implementing a trait on a type is similar to implementing regular methods. The difference is that after impl, we put the trait name we want to implement, then use the for keyword, and then specify the name of the type we want to implement the trait for. Within the impl block, we put the method signatures that the trait definition has defined. Instead of adding a semicolon after each signature, we use curly brackets and fill in the method body with the specific behavior that we want the methods of the trait to have for the particular type.

Now that the library has implemented the Summary trait on NewsArticle and Tweet, users of the crate can call the trait methods on instances of NewsArticle and Tweet in the same way we call regular methods. The only difference is that the user must bring the trait into scope as well as the types. Here’s an example of how a binary crate could use our aggregator library crate:

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());
}

This code prints 1 new tweet: horse_ebooks: of course, as you probably already know, people.

Other crates that depend on the aggregator crate can also bring the Summary trait into scope to implement Summary on their own types. One restriction to note is that we can implement a trait on a type only if at least one of the trait or the type is local to our crate. For example, we can implement standard library traits like Display on a custom type like Tweet as part of our aggregator crate functionality, because the type Tweet is local to our aggregator crate. We can also implement Summary on Vec<T> in our aggregator crate, because the trait Summary is local to our aggregator crate.

But we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec<T> within our aggregator crate, because Display and Vec<T> are both defined in the standard library and aren’t local to our aggregator crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use.

Default Implementations

Sometimes it’s useful to have default behavior for some or all of the methods in a trait instead of requiring implementations for all methods on every type. Then, as we implement the trait on a particular type, we can keep or override each method’s default behavior.

In Listing 10-14 we specify a default string for the summarize method of the Summary trait instead of only defining the method signature, as we did in Listing 10-12.

Filename: 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)
    }
}

Listing 10-14: Defining a Summary trait with a default implementation of the summarize method

To use a default implementation to summarize instances of NewsArticle, we specify an empty impl block with impl Summary for NewsArticle {}.

Even though we’re no longer defining the summarize method on NewsArticle directly, we’ve provided a default implementation and specified that NewsArticle implements the Summary trait. As a result, we can still call the summarize method on an instance of NewsArticle, like this:

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());
}

This code prints New article available! (Read more...).

Creating a default implementation doesn’t require us to change anything about the implementation of Summary on Tweet in Listing 10-13. The reason is that the syntax for overriding a default implementation is the same as the syntax for implementing a trait method that doesn’t have a default implementation.

Default implementations can call other methods in the same trait, even if those other methods don’t have a default implementation. In this way, a trait can provide a lot of useful functionality and only require implementors to specify a small part of it. For example, we could define the Summary trait to have a summarize_author method whose implementation is required, and then define a summarize method that has a default implementation that calls the summarize_author method:

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)
    }
}

To use this version of Summary, we only need to define summarize_author when we implement the trait on a type:

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)
    }
}

After we define summarize_author, we can call summarize on instances of the Tweet struct, and the default implementation of summarize will call the definition of summarize_author that we’ve provided. Because we’ve implemented summarize_author, the Summary trait has given us the behavior of the summarize method without requiring us to write any more code.

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());
}

This code prints 1 new tweet: (Read more from @horse_ebooks...).

Note that it isn’t possible to call the default implementation from an overriding implementation of that same method.

Traits as Parameters

Now that you know how to define and implement traits, we can explore how to use traits to define functions that accept many different types. We'll use the Summary trait we implemented on the NewsArticle and Tweet types in Listing 10-13 to define a notify function that calls the summarize method on its item parameter, which is of some type that implements the Summary trait. To do this, we use the impl Trait syntax, like this:

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());
}

Instead of a concrete type for the item parameter, we specify the impl keyword and the trait name. This parameter accepts any type that implements the specified trait. In the body of notify, we can call any methods on item that come from the Summary trait, such as summarize. We can call notify and pass in any instance of NewsArticle or Tweet. Code that calls the function with any other type, such as a String or an i32, won’t compile because those types don’t implement Summary.

Trait Bound Syntax

The impl Trait syntax works for straightforward cases but is actually syntax sugar for a longer form known as a trait bound; it looks like this:

pub fn notify<T: Summary>(item: &T) {
    println!("Breaking news! {}", item.summarize());
}

This longer form is equivalent to the example in the previous section but is more verbose. We place trait bounds with the declaration of the generic type parameter after a colon and inside angle brackets.

The impl Trait syntax is convenient and makes for more concise code in simple cases, while the fuller trait bound syntax can express more complexity in other cases. For example, we can have two parameters that implement Summary. Doing so with the impl Trait syntax looks like this:

pub fn notify(item1: &impl Summary, item2: &impl Summary) {

Using impl Trait is appropriate if we want this function to allow item1 and item2 to have different types (as long as both types implement Summary). If we want to force both parameters to have the same type, however, we must use a trait bound, like this:

pub fn notify<T: Summary>(item1: &T, item2: &T) {

The generic type T specified as the type of the item1 and item2 parameters constrains the function such that the concrete type of the value passed as an argument for item1 and item2 must be the same.

Specifying Multiple Trait Bounds with the + Syntax

We can also specify more than one trait bound. Say we wanted notify to use display formatting as well as summarize on item: we specify in the notify definition that item must implement both Display and Summary. We can do so using the + syntax:

pub fn notify(item: &(impl Summary + Display)) {

The + syntax is also valid with trait bounds on generic types:

pub fn notify<T: Summary + Display>(item: &T) {

With the two trait bounds specified, the body of notify can call summarize and use {} to format item.

Clearer Trait Bounds with where Clauses

Using too many trait bounds has its downsides. Each generic has its own trait bounds, so functions with multiple generic type parameters can contain lots of trait bound information between the function’s name and its parameter list, making the function signature hard to read. For this reason, Rust has alternate syntax for specifying trait bounds inside a where clause after the function signature. So instead of writing this:

fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {

we can use a where clause, like this:

fn some_function<T, U>(t: &T, u: &U) -> i32
where
    T: Display + Clone,
    U: Clone + Debug,
{
    unimplemented!()
}

This function’s signature is less cluttered: the function name, parameter list, and return type are close together, similar to a function without lots of trait bounds.

Returning Types that Implement Traits

We can also use the impl Trait syntax in the return position to return a value of some type that implements a trait, as shown here:

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,
    }
}

By using impl Summary for the return type, we specify that the returns_summarizable function returns some type that implements the Summary trait without naming the concrete type. In this case, returns_summarizable returns a Tweet, but the code calling this function doesn’t need to know that.

The ability to specify a return type only by the trait it implements is especially useful in the context of closures and iterators, which we cover in Chapter 13. Closures and iterators create types that only the compiler knows or types that are very long to specify. The impl Trait syntax lets you concisely specify that a function returns some type that implements the Iterator trait without needing to write out a very long type.

However, you can only use impl Trait if you’re returning a single type. For example, this code that returns either a NewsArticle or a Tweet with the return type specified as impl Summary wouldn’t work:

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,
        }
    }
}

Returning either a NewsArticle or a Tweet isn’t allowed due to restrictions around how the impl Trait syntax is implemented in the compiler. We’ll cover how to write a function with this behavior in the “Using Trait Objects That Allow for Values of Different Types” section of Chapter 17.

Using Trait Bounds to Conditionally Implement Methods

By using a trait bound with an impl block that uses generic type parameters, we can implement methods conditionally for types that implement the specified traits. For example, the type Pair<T> in Listing 10-15 always implements the new function to return a new instance of Pair<T> (recall from the “Defining Methods” section of Chapter 5 that Self is a type alias for the type of the impl block, which in this case is Pair<T>). But in the next impl block, Pair<T> only implements the cmp_display method if its inner type T implements the PartialOrd trait that enables comparison and the Display trait that enables printing.

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);
        }
    }
}

Listing 10-15: Conditionally implementing methods on a generic type depending on trait bounds

We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called blanket implementations and are extensively used in the Rust standard library. For example, the standard library implements the ToString trait on any type that implements the Display trait. The impl block in the standard library looks similar to this code:

impl<T: Display> ToString for T {
    // --snip--
}

Because the standard library has this blanket implementation, we can call the to_string method defined by the ToString trait on any type that implements the Display trait. For example, we can turn integers into their corresponding String values like this because integers implement Display:

#![allow(unused)]
fn main() {
let s = 3.to_string();
}

Blanket implementations appear in the documentation for the trait in the “Implementors” section.

Traits and trait bounds let us write code that uses generic type parameters to reduce duplication but also specify to the compiler that we want the generic type to have particular behavior. The compiler can then use the trait bound information to check that all the concrete types used with our code provide the correct behavior. In dynamically typed languages, we would get an error at runtime if we called a method on a type which didn’t define the method. But Rust moves these errors to compile time so we’re forced to fix the problems before our code is even able to run. Additionally, we don’t have to write code that checks for behavior at runtime because we’ve already checked at compile time. Doing so improves performance without having to give up the flexibility of generics.

Validating References with Lifetimes

Lifetimes are another kind of generic that we’ve already been using. Rather than ensuring that a type has the behavior we want, lifetimes ensure that references are valid as long as we need them to be.

One detail we didn’t discuss in the “References and Borrowing” section in Chapter 4 is that every reference in Rust has a lifetime, which is the scope for which that reference is valid. Most of the time, lifetimes are implicit and inferred, just like most of the time, types are inferred. We only must annotate types when multiple types are possible. In a similar way, we must annotate lifetimes when the lifetimes of references could be related in a few different ways. Rust requires us to annotate the relationships using generic lifetime parameters to ensure the actual references used at runtime will definitely be valid.

Annotating lifetimes is not even a concept most other programming languages have, so this is going to feel unfamiliar. Although we won’t cover lifetimes in their entirety in this chapter, we’ll discuss common ways you might encounter lifetime syntax so you can get comfortable with the concept.

Preventing Dangling References with Lifetimes

The main aim of lifetimes is to prevent dangling references, which cause a program to reference data other than the data it’s intended to reference. Consider the program in Listing 10-16, which has an outer scope and an inner scope.

fn main() {
    let r;

    {
        let x = 5;
        r = &x;
    }

    println!("r: {}", r);
}

Listing 10-16: An attempt to use a reference whose value has gone out of scope

Note: The examples in Listings 10-16, 10-17, and 10-23 declare variables without giving them an initial value, so the variable name exists in the outer scope. At first glance, this might appear to be in conflict with Rust’s having no null values. However, if we try to use a variable before giving it a value, we’ll get a compile-time error, which shows that Rust indeed does not allow null values.

The outer scope declares a variable named r with no initial value, and the inner scope declares a variable named x with the initial value of 5. Inside the inner scope, we attempt to set the value of r as a reference to x. Then the inner scope ends, and we attempt to print the value in r. This code won’t compile because the value r is referring to has gone out of scope before we try to use it. Here is the error message:

$ 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

The variable x doesn’t “live long enough.” The reason is that x will be out of scope when the inner scope ends on line 7. But r is still valid for the outer scope; because its scope is larger, we say that it “lives longer.” If Rust allowed this code to work, r would be referencing memory that was deallocated when x went out of scope, and anything we tried to do with r wouldn’t work correctly. So how does Rust determine that this code is invalid? It uses a borrow checker.

The Borrow Checker

The Rust compiler has a borrow checker that compares scopes to determine whether all borrows are valid. Listing 10-17 shows the same code as Listing 10-16 but with annotations showing the lifetimes of the variables.

fn main() {
    let r;                // ---------+-- 'a
                          //          |
    {                     //          |
        let x = 5;        // -+-- 'b  |
        r = &x;           //  |       |
    }                     // -+       |
                          //          |
    println!("r: {}", r); //          |
}                         // ---------+

Listing 10-17: Annotations of the lifetimes of r and x, named 'a and 'b, respectively

Here, we’ve annotated the lifetime of r with 'a and the lifetime of x with 'b. As you can see, the inner 'b block is much smaller than the outer 'a lifetime block. At compile time, Rust compares the size of the two lifetimes and sees that r has a lifetime of 'a but that it refers to memory with a lifetime of 'b. The program is rejected because 'b is shorter than 'a: the subject of the reference doesn’t live as long as the reference.

Listing 10-18 fixes the code so it doesn’t have a dangling reference and compiles without any errors.

fn main() {
    let x = 5;            // ----------+-- 'b
                          //           |
    let r = &x;           // --+-- 'a  |
                          //   |       |
    println!("r: {}", r); //   |       |
                          // --+       |
}                         // ----------+

Listing 10-18: A valid reference because the data has a longer lifetime than the reference

Here, x has the lifetime 'b, which in this case is larger than 'a. This means r can reference x because Rust knows that the reference in r will always be valid while x is valid.

Now that you know where the lifetimes of references are and how Rust analyzes lifetimes to ensure references will always be valid, let’s explore generic lifetimes of parameters and return values in the context of functions.

Generic Lifetimes in Functions

We’ll write a function that returns the longer of two string slices. This function will take two string slices and return a single string slice. After we’ve implemented the longest function, the code in Listing 10-19 should print The longest string is abcd.

Filename: 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);
}

Listing 10-19: A main function that calls the longest function to find the longer of two string slices

Note that we want the function to take string slices, which are references, rather than strings, because we don’t want the longest function to take ownership of its parameters. Refer to the “String Slices as Parameters” section in Chapter 4 for more discussion about why the parameters we use in Listing 10-19 are the ones we want.

If we try to implement the longest function as shown in Listing 10-20, it won’t compile.

Filename: 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
    }
}

Listing 10-20: An implementation of the longest function that returns the longer of two string slices but does not yet compile

Instead, we get the following error that talks about 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

The help text reveals that the return type needs a generic lifetime parameter on it because Rust can’t tell whether the reference being returned refers to x or y. Actually, we don’t know either, because the if block in the body of this function returns a reference to x and the else block returns a reference to y!

When we’re defining this function, we don’t know the concrete values that will be passed into this function, so we don’t know whether the if case or the else case will execute. We also don’t know the concrete lifetimes of the references that will be passed in, so we can’t look at the scopes as we did in Listings 10-17 and 10-18 to determine whether the reference we return will always be valid. The borrow checker can’t determine this either, because it doesn’t know how the lifetimes of x and y relate to the lifetime of the return value. To fix this error, we’ll add generic lifetime parameters that define the relationship between the references so the borrow checker can perform its analysis.

Lifetime Annotation Syntax

Lifetime annotations don’t change how long any of the references live. Rather, they describe the relationships of the lifetimes of multiple references to each other without affecting the lifetimes. Just as functions can accept any type when the signature specifies a generic type parameter, functions can accept references with any lifetime by specifying a generic lifetime parameter.

Lifetime annotations have a slightly unusual syntax: the names of lifetime parameters must start with an apostrophe (') and are usually all lowercase and very short, like generic types. Most people use the name 'a for the first lifetime annotation. We place lifetime parameter annotations after the & of a reference, using a space to separate the annotation from the reference’s type.

Here are some examples: a reference to an i32 without a lifetime parameter, a reference to an i32 that has a lifetime parameter named 'a, and a mutable reference to an i32 that also has the lifetime 'a.

&i32        // a reference
&'a i32     // a reference with an explicit lifetime
&'a mut i32 // a mutable reference with an explicit lifetime

One lifetime annotation by itself doesn’t have much meaning, because the annotations are meant to tell Rust how generic lifetime parameters of multiple references relate to each other. Let’s examine how the lifetime annotations relate to each other in the context of the longest function.

Lifetime Annotations in Function Signatures

To use lifetime annotations in function signatures, we need to declare the generic lifetime parameters inside angle brackets between the function name and the parameter list, just as we did with generic type parameters.

We want the signature to express the following constraint: the returned reference will be valid as long as both the parameters are valid. This is the relationship between lifetimes of the parameters and the return value. We’ll name the lifetime 'a and then add it to each reference, as shown in Listing 10-21.

Filename: 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
    }
}

Listing 10-21: The longest function definition specifying that all the references in the signature must have the same lifetime 'a

This code should compile and produce the result we want when we use it with the main function in Listing 10-19.

The function signature now tells Rust that for some lifetime 'a, the function takes two parameters, both of which are string slices that live at least as long as lifetime 'a. The function signature also tells Rust that the string slice returned from the function will live at least as long as lifetime 'a. In practice, it means that the lifetime of the reference returned by the longest function is the same as the smaller of the lifetimes of the values referred to by the function arguments. These relationships are what we want Rust to use when analyzing this code.

Remember, when we specify the lifetime parameters in this function signature, we’re not changing the lifetimes of any values passed in or returned. Rather, we’re specifying that the borrow checker should reject any values that don’t adhere to these constraints. Note that the longest function doesn’t need to know exactly how long x and y will live, only that some scope can be substituted for 'a that will satisfy this signature.

When annotating lifetimes in functions, the annotations go in the function signature, not in the function body. The lifetime annotations become part of the contract of the function, much like the types in the signature. Having function signatures contain the lifetime contract means the analysis the Rust compiler does can be simpler. If there’s a problem with the way a function is annotated or the way it is called, the compiler errors can point to the part of our code and the constraints more precisely. If, instead, the Rust compiler made more inferences about what we intended the relationships of the lifetimes to be, the compiler might only be able to point to a use of our code many steps away from the cause of the problem.

When we pass concrete references to longest, the concrete lifetime that is substituted for 'a is the part of the scope of x that overlaps with the scope of y. In other words, the generic lifetime 'a will get the concrete lifetime that is equal to the smaller of the lifetimes of x and y. Because we’ve annotated the returned reference with the same lifetime parameter 'a, the returned reference will also be valid for the length of the smaller of the lifetimes of x and y.

Let’s look at how the lifetime annotations restrict the longest function by passing in references that have different concrete lifetimes. Listing 10-22 is a straightforward example.

Filename: 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
    }
}

Listing 10-22: Using the longest function with references to String values that have different concrete lifetimes

In this example, string1 is valid until the end of the outer scope, string2 is valid until the end of the inner scope, and result references something that is valid until the end of the inner scope. Run this code, and you’ll see that the borrow checker approves; it will compile and print The longest string is long string is long.

Next, let’s try an example that shows that the lifetime of the reference in result must be the smaller lifetime of the two arguments. We’ll move the declaration of the result variable outside the inner scope but leave the assignment of the value to the result variable inside the scope with string2. Then we’ll move the println! that uses result to outside the inner scope, after the inner scope has ended. The code in Listing 10-23 will not compile.

Filename: 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
    }
}

Listing 10-23: Attempting to use result after string2 has gone out of scope

When we try to compile this code, we get this error:

$ 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

The error shows that for result to be valid for the println! statement, string2 would need to be valid until the end of the outer scope. Rust knows this because we annotated the lifetimes of the function parameters and return values using the same lifetime parameter 'a.

As humans, we can look at this code and see that string1 is longer than string2 and therefore result will contain a reference to string1. Because string1 has not gone out of scope yet, a reference to string1 will still be valid for the println! statement. However, the compiler can’t see that the reference is valid in this case. We’ve told Rust that the lifetime of the reference returned by the longest function is the same as the smaller of the lifetimes of the references passed in. Therefore, the borrow checker disallows the code in Listing 10-23 as possibly having an invalid reference.

Try designing more experiments that vary the values and lifetimes of the references passed in to the longest function and how the returned reference is used. Make hypotheses about whether or not your experiments will pass the borrow checker before you compile; then check to see if you’re right!

Thinking in Terms of Lifetimes

The way in which you need to specify lifetime parameters depends on what your function is doing. For example, if we changed the implementation of the longest function to always return the first parameter rather than the longest string slice, we wouldn’t need to specify a lifetime on the y parameter. The following code will compile:

Filename: 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
}

We’ve specified a lifetime parameter 'a for the parameter x and the return type, but not for the parameter y, because the lifetime of y does not have any relationship with the lifetime of x or the return value.

When returning a reference from a function, the lifetime parameter for the return type needs to match the lifetime parameter for one of the parameters. If the reference returned does not refer to one of the parameters, it must refer to a value created within this function. However, this would be a dangling reference because the value will go out of scope at the end of the function. Consider this attempted implementation of the longest function that won’t compile:

Filename: 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()
}

Here, even though we’ve specified a lifetime parameter 'a for the return type, this implementation will fail to compile because the return value lifetime is not related to the lifetime of the parameters at all. Here is the error message we get:

$ 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

The problem is that result goes out of scope and gets cleaned up at the end of the longest function. We’re also trying to return a reference to result from the function. There is no way we can specify lifetime parameters that would change the dangling reference, and Rust won’t let us create a dangling reference. In this case, the best fix would be to return an owned data type rather than a reference so the calling function is then responsible for cleaning up the value.

Ultimately, lifetime syntax is about connecting the lifetimes of various parameters and return values of functions. Once they’re connected, Rust has enough information to allow memory-safe operations and disallow operations that would create dangling pointers or otherwise violate memory safety.

Lifetime Annotations in Struct Definitions

So far, the structs we’ve defined all hold owned types. We can define structs to hold references, but in that case we would need to add a lifetime annotation on every reference in the struct’s definition. Listing 10-24 has a struct named ImportantExcerpt that holds a string slice.

Filename: 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,
    };
}

Listing 10-24: A struct that holds a reference, requiring a lifetime annotation

This struct has the single field part that holds a string slice, which is a reference. As with generic data types, we declare the name of the generic lifetime parameter inside angle brackets after the name of the struct so we can use the lifetime parameter in the body of the struct definition. This annotation means an instance of ImportantExcerpt can’t outlive the reference it holds in its part field.

The main function here creates an instance of the ImportantExcerpt struct that holds a reference to the first sentence of the String owned by the variable novel. The data in novel exists before the ImportantExcerpt instance is created. In addition, novel doesn’t go out of scope until after the ImportantExcerpt goes out of scope, so the reference in the ImportantExcerpt instance is valid.

Lifetime Elision

You’ve learned that every reference has a lifetime and that you need to specify lifetime parameters for functions or structs that use references. However, in Chapter 4 we had a function in Listing 4-9, shown again in Listing 10-25, that compiled without lifetime annotations.

Filename: 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);
}

Listing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references

The reason this function compiles without lifetime annotations is historical: in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because every reference needed an explicit lifetime. At that time, the function signature would have been written like this:

fn first_word<'a>(s: &'a str) -> &'a str {

After writing a lot of Rust code, the Rust team found that Rust programmers were entering the same lifetime annotations over and over in particular situations. These situations were predictable and followed a few deterministic patterns. The developers programmed these patterns into the compiler’s code so the borrow checker could infer the lifetimes in these situations and wouldn’t need explicit annotations.

This piece of Rust history is relevant because it’s possible that more deterministic patterns will emerge and be added to the compiler. In the future, even fewer lifetime annotations might be required.

The patterns programmed into Rust’s analysis of references are called the lifetime elision rules. These aren’t rules for programmers to follow; they’re a set of particular cases that the compiler will consider, and if your code fits these cases, you don’t need to write the lifetimes explicitly.

The elision rules don’t provide full inference. If Rust deterministically applies the rules but there is still ambiguity as to what lifetimes the references have, the compiler won’t guess what the lifetime of the remaining references should be. Instead of guessing, the compiler will give you an error that you can resolve by adding the lifetime annotations.

Lifetimes on function or method parameters are called input lifetimes, and lifetimes on return values are called output lifetimes.

The compiler uses three rules to figure out the lifetimes of the references when there aren’t explicit annotations. The first rule applies to input lifetimes, and the second and third rules apply to output lifetimes. If the compiler gets to the end of the three rules and there are still references for which it can’t figure out lifetimes, the compiler will stop with an error. These rules apply to fn definitions as well as impl blocks.

The first rule is that the compiler assigns a lifetime parameter to each parameter that’s a reference. In other words, a function with one parameter gets one lifetime parameter: fn foo<'a>(x: &'a i32); a function with two parameters gets two separate lifetime parameters: fn foo<'a, 'b>(x: &'a i32, y: &'b i32); and so on.

The second rule is that, if there is exactly one input lifetime parameter, that lifetime is assigned to all output lifetime parameters: fn foo<'a>(x: &'a i32) -> &'a i32.

The third rule is that, if there are multiple input lifetime parameters, but one of them is &self or &mut self because this is a method, the lifetime of self is assigned to all output lifetime parameters. This third rule makes methods much nicer to read and write because fewer symbols are necessary.

Let’s pretend we’re the compiler. We’ll apply these rules to figure out the lifetimes of the references in the signature of the first_word function in Listing 10-25. The signature starts without any lifetimes associated with the references:

fn first_word(s: &str) -> &str {

Then the compiler applies the first rule, which specifies that each parameter gets its own lifetime. We’ll call it 'a as usual, so now the signature is this:

fn first_word<'a>(s: &'a str) -> &str {

The second rule applies because there is exactly one input lifetime. The second rule specifies that the lifetime of the one input parameter gets assigned to the output lifetime, so the signature is now this:

fn first_word<'a>(s: &'a str) -> &'a str {

Now all the references in this function signature have lifetimes, and the compiler can continue its analysis without needing the programmer to annotate the lifetimes in this function signature.

Let’s look at another example, this time using the longest function that had no lifetime parameters when we started working with it in Listing 10-20:

fn longest(x: &str, y: &str) -> &str {

Let’s apply the first rule: each parameter gets its own lifetime. This time we have two parameters instead of one, so we have two lifetimes:

fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {

You can see that the second rule doesn’t apply because there is more than one input lifetime. The third rule doesn’t apply either, because longest is a function rather than a method, so none of the parameters are self. After working through all three rules, we still haven’t figured out what the return type’s lifetime is. This is why we got an error trying to compile the code in Listing 10-20: the compiler worked through the lifetime elision rules but still couldn’t figure out all the lifetimes of the references in the signature.

Because the third rule really only applies in method signatures, we’ll look at lifetimes in that context next to see why the third rule means we don’t have to annotate lifetimes in method signatures very often.

Lifetime Annotations in Method Definitions

When we implement methods on a struct with lifetimes, we use the same syntax as that of generic type parameters shown in Listing 10-11. Where we declare and use the lifetime parameters depends on whether they’re related to the struct fields or the method parameters and return values.

Lifetime names for struct fields always need to be declared after the impl keyword and then used after the struct’s name, because those lifetimes are part of the struct’s type.

In method signatures inside the impl block, references might be tied to the lifetime of references in the struct’s fields, or they might be independent. In addition, the lifetime elision rules often make it so that lifetime annotations aren’t necessary in method signatures. Let’s look at some examples using the struct named ImportantExcerpt that we defined in Listing 10-24.

First, we’ll use a method named level whose only parameter is a reference to self and whose return value is an i32, which is not a reference to anything:

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,
    };
}

The lifetime parameter declaration after impl and its use after the type name are required, but we’re not required to annotate the lifetime of the reference to self because of the first elision rule.

Here is an example where the third lifetime elision rule applies:

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,
    };
}

There are two input lifetimes, so Rust applies the first lifetime elision rule and gives both &self and announcement their own lifetimes. Then, because one of the parameters is &self, the return type gets the lifetime of &self, and all lifetimes have been accounted for.

The Static Lifetime

One special lifetime we need to discuss is 'static, which denotes that the affected reference can live for the entire duration of the program. All string literals have the 'static lifetime, which we can annotate as follows:

#![allow(unused)]
fn main() {
let s: &'static str = "I have a static lifetime.";
}

The text of this string is stored directly in the program’s binary, which is always available. Therefore, the lifetime of all string literals is 'static.

You might see suggestions to use the 'static lifetime in error messages. But before specifying 'static as the lifetime for a reference, think about whether the reference you have actually lives the entire lifetime of your program or not, and whether you want it to. Most of the time, an error message suggesting the 'static lifetime results from attempting to create a dangling reference or a mismatch of the available lifetimes. In such cases, the solution is fixing those problems, not specifying the 'static lifetime.

Generic Type Parameters, Trait Bounds, and Lifetimes Together

Let’s briefly look at the syntax of specifying generic type parameters, trait bounds, and lifetimes all in one function!

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
    }
}

This is the longest function from Listing 10-21 that returns the longer of two string slices. But now it has an extra parameter named ann of the generic type T, which can be filled in by any type that implements the Display trait as specified by the where clause. This extra parameter will be printed using {}, which is why the Display trait bound is necessary. Because lifetimes are a type of generic, the declarations of the lifetime parameter 'a and the generic type parameter T go in the same list inside the angle brackets after the function name.

Summary

We covered a lot in this chapter! Now that you know about generic type parameters, traits and trait bounds, and generic lifetime parameters, you’re ready to write code without repetition that works in many different situations. Generic type parameters let you apply the code to different types. Traits and trait bounds ensure that even though the types are generic, they’ll have the behavior the code needs. You learned how to use lifetime annotations to ensure that this flexible code won’t have any dangling references. And all of this analysis happens at compile time, which doesn’t affect runtime performance!

Believe it or not, there is much more to learn on the topics we discussed in this chapter: Chapter 17 discusses trait objects, which are another way to use traits. There are also more complex scenarios involving lifetime annotations that you will only need in very advanced scenarios; for those, you should read the Rust Reference. But next, you’ll learn how to write tests in Rust so you can make sure your code is working the way it should.

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:

  1. Set up any needed data or state.
  2. Run the code you want to test.
  3. 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);
    }
}

Listing 11-1: The test module and function generated automatically by cargo new

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

Listing 11-2: The output from running the automatically generated test

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");
    }
}

Listing 11-3: Adding a second test that will fail because we call the panic! macro

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`

Listing 11-4: Test results when one test passes and one test fails

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
    }
}

Listing 11-5: Using the Rectangle struct and its can_hold method from Chapter 5

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));
    }
}

Listing 11-6: A test for can_hold that checks whether a larger rectangle can indeed hold a smaller rectangle

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));
    }
}

Listing 11-7: Testing the function add_two using the assert_eq! macro

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);
    }
}

Listing 11-8: Testing that a condition will cause a panic!

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);
    }
}

Listing 11-9: Testing for a panic! with a panic message containing a specified substring

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);
    }
}

Listing 11-10: Tests for a function that calls println!

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));
    }
}

Listing 11-11: Three tests with three different names

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));
    }
}

Listing 11-12: Testing a private function

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));
}

Listing 11-13: An integration test of a function in the adder crate

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:

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);
}

Listing 12-1: Collecting the command line arguments into a vector and printing them

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 Unicode

Note that std::env::args will panic if any argument contains invalid Unicode. If your program needs to accept arguments containing invalid Unicode, use std::env::args_os instead. That function returns an iterator that produces OsString values instead of String values. We’ve chosen to use std::env::args here for simplicity, because OsString values differ per platform and are more complex to work with than String 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);
}

Listing 12-2: Creating variables to hold the query argument and file path argument

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!

Listing 12-3: A poem by Emily Dickinson makes a good test case

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}");
}

Listing 12-4: Reading the contents of the file specified by the second argument

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)
}

Listing 12-5: Extracting a parse_config function from main

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 }
}

Listing 12-6: Refactoring parse_config to return an instance of a Config struct

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 call clone.

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 }
    }
}

Listing 12-7: Changing parse_config into Config::new

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 }
    }
}

Listing 12-8: Adding a check for the number of arguments

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 })
    }
}

Listing 12-9: Returning a Result from Config::build

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 })
    }
}

Listing 12-10: Exiting with an error code if building a Config fails

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 })
    }
}

Listing 12-11: Extracting a run function containing the rest of the program logic

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 })
    }
}

Listing 12-12: Changing the run function to return Result

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(())
}

Listing 12-13: Moving Config and run into src/lib.rs

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);
    }
}

Listing 12-14: Using the minigrep library crate in src/main.rs

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:

  1. Write a test that fails and run it to make sure it fails for the reason you expect.
  2. Write or modify just enough code to make the new test pass.
  3. Refactor the code you just added or changed and make sure the tests continue to pass.
  4. 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));
    }
}

Listing 12-15: Creating a failing test for the search function we wish we had

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));
    }
}

Listing 12-16: Defining just enough of the search function so our test will compile

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));
    }
}

Listing 12-17: Iterating through each line in 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));
    }
}

Listing 12-18: Adding functionality to see whether the line contains the string in query

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));
    }
}

Listing 12-19: Storing the lines that match so we can return them

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)
        );
    }
}

Listing 12-20: Adding a new failing test for the case-insensitive function we’re about to add

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)
        );
    }
}

Listing 12-21: Defining the search_case_insensitive function to lowercase the query and the line before comparing them

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)
        );
    }
}

Listing 12-22: Calling either search or search_case_insensitive based on the value in config.ignore_case

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)
        );
    }
}

Listing 12-23: Checking for any value in an environment variable named IGNORE_CASE

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);
    }
}

Listing 12-24: Writing error messages to standard error instead of standard output using eprintln!

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
    );
}

Listing 13-1: Shirt company giveaway situation

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);
}

Listing 13-2: Adding optional type annotations of the parameter and return value types in the closure

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);
}

Listing 13-3: Attempting to call a closure whose types are inferred with two different types

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);
}

Listing 13-4: Defining and calling a closure that captures an immutable reference

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);
}

Listing 13-5: Defining and calling a closure that captures a mutable reference

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();
}

Listing 13-6: Using move to force the closure for the thread to take ownership of list

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:

  1. 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 implement FnOnce and none of the other Fn traits, because it can only be called once.
  2. 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.
  3. 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 the Fn traits. For example, on an Option<Vec<T>> value, we could call unwrap_or_else(Vec::new) to get a new, empty vector if the value is None.

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);
}

Listing 13-7: Using sort_by_key to order rectangles by width

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);
}

Listing 13-8: Attempting to use an FnOnce closure with sort_by_key

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);
}

Listing 13-9: Using an FnMut closure with sort_by_key is allowed

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();
}

Listing 13-10: Creating an iterator

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);
    }
}

Listing 13-11: Using an iterator in a for loop

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);
    }
}

Listing 13-12: Calling the next method on an iterator

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);
    }
}

Listing 13-13: Calling the sum method to get the total of all items in the iterator

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);
}

Listing 13-14: Calling the iterator adaptor map to create a new iterator

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]);
}

Listing 13-15: Calling the map method to create a new iterator and then calling the collect method to consume the new iterator and create a vector

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")
                },
            ]
        );
    }
}

Listing 13-16: Using the filter method with a closure that captures shoe_size

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)
        );
    }
}

Listing 13-17: Reproduction of the Config::build function from Listing 12-23

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);
    }
}

Listing 13-18: Passing the return value of env::args to Config::build

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)
        );
    }
}

Listing 13-19: Updating the signature of Config::build to expect an iterator

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)
        );
    }
}

Listing 13-20: Changing the body of Config::build to use iterator methods

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));
    }
}

Listing 13-21: The implementation of the search function from Listing 12-19

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)
        );
    }
}

Listing 13-22: Using iterator adaptor methods in the implementation of the search function

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
}

Listing 14-1: A documentation comment for a function

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:

Rendered HTML documentation for the `add_one` function of `my_crate`

Figure 14-1: HTML documentation for the add_one function

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
}

Listing 14-2: Documentation for the my_crate crate as a whole

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:

Rendered HTML documentation with a comment for the crate as a whole

Figure 14-2: Rendered documentation for my_crate, including the comment describing the crate as a whole

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!();
    }
}

Listing 14-3: An art library with items organized into kinds and utils modules

Figure 14-3 shows what the front page of the documentation for this crate generated by cargo doc would look like:

Rendered documentation for the `art` crate that lists the `kinds` and `utils` modules

Figure 14-3: Front page of the documentation for art that lists the kinds and utils modules

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);
}

Listing 14-4: A crate using the art crate’s items with its internal structure exported

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
    }
}

Listing 14-5: Adding pub use statements to re-export items

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.

Rendered documentation for the `art` crate with the re-exports on the front page

Figure 14-4: The front page of the documentation for art that lists the re-exports

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);
}

Listing 14-6: A program using the re-exported items from the art crate

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
}