Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Введение

Note: This edition of the book is the same as The Rust Programming Language available in print and ebook format from No Starch Press.

Добро пожаловать в The Rust Programming Language — ознакомительную книгу о Rust. Язык программирования Rust поможет вам быстро писать более надёжное программное обеспечение. Высокоуровневая эргономика и низкоуровневый контроль часто становятся несовместимыми целями при разработке нового языка программирования. Rust бросает вызов этому противоречию. Балансируя между мощной технической выразительностью и простотой логики программ, Rust даёт вам возможность управлять низкоуровневыми деталями (например, использованием памяти) без хлопот, обычно ожидаемых от необходимости подобного контроля.

Кому Rust придётся по душе

Ряд особенностей Rust делает его превосходным для многих групп людей. Взглянем на некоторые наиболее важные из них.

Команды разработчиков

Rust is proving to be a productive tool for collaborating among large teams of developers with varying levels of systems programming knowledge. Low-level code is prone to various subtle bugs, which in most other languages can only be caught through extensive testing and careful code review by experienced developers. In Rust, the compiler plays a gatekeeper role by refusing to compile code with these elusive bugs, including concurrency bugs. By working alongside the compiler, the team can spend its time focusing on the program’s logic rather than chasing down bugs.

Rust также привносит современные инструменты разработки в мир системного программирования:

  • Cargo — встроенный менеджер зависимостей и инструмент сборки, делающий добавление,компиляцию и управление зависимостей безпроблемным и согласованным в рамках всей экосистемыRust.
  • The rustfmt formatting tool ensures a consistent coding style across developers.
  • The Rust Language Server powers integrated development environment (IDE) integration for code completion and inline error messages.

Благодаря применению этих и других инструментов экосистемы Rust, разработчики способны продуктивно работать над программами системного уровня.

Учащиеся

Rust is for students and those who are interested in learning about systems concepts. Using Rust, many people have learned about topics like operating systems development. The community is very welcoming and happy to answer students’ questions. Through efforts such as this book, the Rust teams want to make systems concepts more accessible to more people, especially those new to programming.

Компании

Сотни компаний, больших и маленьких, применяют Rust для множества задач, таких как разработка инструментов командной строки, веб-сервисов, инструментов DevOps, встраиваемых устройств; анализ и обработка аудио и видео; создание криптовалют; биоинформатика; разработка поисковых систем, приложений интернета вещей; машинное обучение; и, наконец и например, разработка основных частей браузера Firefox.

Разработчики открытого программного обеспечения

Мир Rust с радостью примет людей, желающих развить этот язык, построить сплочённое Сообщество, создать библиотеки и средства разработки. Мы будем благодарны за ваш вклад в Rust.

Люди, ценящие скорость и устойчивость

Rust будет приятен для людей, требующих от языка скорости и стабильности. Под скоростью мы понимаем как скорость исполения программ, так и скорость их разработки. Проверки компилятора Rust гарантируют стабильность при развитии и рефакторинге. Это выгодно отличает Rust от языков, не поддерживающих эти проверки, и потому накопивших большие кодовые базы, которые разработчики часто опасаются редактировать. Благодаря абстракциям с нулевой стоимостью (высокоуровневым механизмам, компилирующимся в низкоуровневый код, столь же быстрый, как и написанный вручную), Rust стремится сделать код и безопасным, и быстрым.

The Rust language hopes to support many other users as well; those mentioned here are merely some of the biggest stakeholders. Overall, Rust’s greatest ambition is to eliminate the trade-offs that programmers have accepted for decades by providing safety and productivity, speed and ergonomics. Give Rust a try, and see if its choices work for you.

Кому будет полезна эта книга

This book assumes that you’ve written code in another programming language, but it doesn’t make any assumptions about which one. We’ve tried to make the material broadly accessible to those from a wide variety of programming backgrounds. We don’t spend a lot of time talking about what programming is or how to think about it. If you’re entirely new to programming, you would be better served by reading a book that specifically provides an introduction to programming.

Как читать эту книгу

Эта книга предполагает, что вы будете её читать последовательно, от начала до конца. Последующие главы опираются на изученное в предыдущих, и более ранние могут охватывать отдельные темы лишь поверхностно, с учётом того, что всё пропущенное будет подробно рассмотрено далее.

You’ll find two kinds of chapters in this book: concept chapters and project chapters. In concept chapters, you’ll learn about an aspect of Rust. In project chapters, we’ll build small programs together, applying what you’ve learned so far. Chapter 2, Chapter 12, and Chapter 21 are project chapters; the rest are concept chapters.

Chapter 1 explains how to install Rust, how to write a “Hello, world!” program, and how to use Cargo, Rust’s package manager and build tool. Chapter 2 is a hands-on introduction to writing a program in Rust, having you build up a number-guessing game. Here, we cover concepts at a high level, and later chapters will provide additional detail. If you want to get your hands dirty right away, Chapter 2 is the place for that. If you’re a particularly meticulous learner who prefers to learn every detail before moving on to the next, you might want to skip Chapter 2 and go straight to Chapter 3, which covers Rust features that are similar to those of other programming languages; then, you can return to Chapter 2 when you’d like to work on a project applying the details you’ve learned.

In Chapter 4, you’ll learn about Rust’s ownership system. Chapter 5 discusses structs and methods. Chapter 6 covers enums, match expressions, and the if let and let...else control flow constructs. You’ll use structs and enums to make custom types.

In Chapter 7, you’ll learn about Rust’s module system and about privacy rules for organizing your code and its public application programming interface (API). Chapter 8 discusses some common collection data structures that the standard library provides: vectors, strings, and hash maps. Chapter 9 explores Rust’s error-handling philosophy and techniques.

Chapter 10 digs into generics, traits, and lifetimes, which give you the power to define code that applies to multiple types. Chapter 11 is all about testing, which even with Rust’s safety guarantees is necessary to ensure that your program’s logic is correct. In Chapter 12, we’ll build our own implementation of a subset of functionality from the grep command line tool that searches for text within files. For this, we’ll use many of the concepts we discussed in the previous chapters.

Chapter 13 explores closures and iterators: features of Rust that come from functional programming languages. In Chapter 14, we’ll examine Cargo in more depth and talk about best practices for sharing your libraries with others. Chapter 15 discusses smart pointers that the standard library provides and the traits that enable their functionality.

In Chapter 16, we’ll walk through different models of concurrent programming and talk about how Rust helps you program in multiple threads fearlessly. In Chapter 17, we build on that by exploring Rust’s async and await syntax, along with tasks, futures, and streams, and the lightweight concurrency model they enable.

Chapter 18 looks at how Rust idioms compare to object-oriented programming principles you might be familiar with. Chapter 19 is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. Chapter 20 contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures.

In Chapter 21, we’ll complete a project in which we’ll implement a low-level multithreaded web server!

Наконец, есть несколько приложений, содержащих полезную информацию о языке в более сухом, справочном виде. В Приложении A рассматриваются ключевые слова Rust; в Приложении B — операторы и символы; в Приложении C — выводимые трейты, предоставляемые стандартной библиотекой; в Приложении D — некоторые полезные инструменты разработки; в Приложении E — редакции Rust. В Приложении F вы найдёте переводы этой книги, а в Приложении G вы узнаете, как разрабатывается Rust и что такое Nightly Rust. (Примечание переводчика: переводы, перечисленные в Приложении F, выполнены в сторонних разрозненных репозиториях. Переводы, выполненные в этой системе, всегда доступны в меню по кнопке глобуса справа сверху.)

There is no wrong way to read this book: If you want to skip ahead, go for it! You might have to jump back to earlier chapters if you experience any confusion. But do whatever works for you.

An important part of the process of learning Rust is learning how to read the error messages the compiler displays: These will guide you toward working code. As such, we’ll provide many examples that don’t compile along with the error message the compiler will show you in each situation. Know that if you enter and run a random example, it may not compile! Make sure you read the surrounding text to see whether the example you’re trying to run is meant to error. In most situations, we’ll lead you to the correct version of any code that doesn’t compile. Ferris will also help you distinguish code that isn’t meant to work:

ФеррисЧто имеет в виду
Феррис со знаком вопросаЭтот код не компилируется!
Феррис воздел клешни вверхЭтот код приведёт к панике!
Феррис поднял одну клешню, как бы пожимая плечамиЭтот код ведёт себя не так, как задумано.

В большинстве случаев, мы приведём вас к исправленной версии неправильных примеров.

Исходный код

Исходные файлы, из которых сгенерирована эта книга, можно найти на GitHub.