├── AUTHORS.md ├── CONTRIBUTING.md ├── README.md ├── README.rev.template.md ├── book.toml ├── cover.jpg ├── docs ├── .nojekyll ├── 404.html ├── FontAwesome │ ├── css │ │ └── font-awesome.css │ └── fonts │ │ ├── FontAwesome.ttf │ │ ├── fontawesome-webfont.eot │ │ ├── fontawesome-webfont.svg │ │ ├── fontawesome-webfont.ttf │ │ ├── fontawesome-webfont.woff │ │ └── fontawesome-webfont.woff2 ├── INTRODUCTION.html ├── ace.js ├── advanced-linking.html ├── associated-constants.html ├── associated-types.html ├── attributes.html ├── ayu-highlight.css ├── benchmark-tests.html ├── bibliography.html ├── book.js ├── borrow-and-asref.html ├── box-syntax-and-patterns.html ├── casting-between-types.html ├── choosing-your-guarantees.html ├── clipboard.min.js ├── closures.html ├── comments.html ├── compiler-plugins.html ├── concurrency.html ├── conditional-compilation.html ├── const-and-static.html ├── crates-and-modules.html ├── css │ ├── chrome.css │ ├── general.css │ ├── print.css │ └── variables.css ├── custom-allocators.html ├── deref-coercions.html ├── dining-philosophers.html ├── documentation.html ├── drop.html ├── editor.js ├── effective-rust.html ├── elasticlunr.min.js ├── enums.html ├── error-handling.html ├── favicon.png ├── favicon.svg ├── ffi.html ├── fonts │ ├── OPEN-SANS-LICENSE.txt │ ├── SOURCE-CODE-PRO-LICENSE.txt │ ├── fonts.css │ ├── open-sans-v17-all-charsets-300.woff2 │ ├── open-sans-v17-all-charsets-300italic.woff2 │ ├── open-sans-v17-all-charsets-600.woff2 │ ├── open-sans-v17-all-charsets-600italic.woff2 │ ├── open-sans-v17-all-charsets-700.woff2 │ ├── open-sans-v17-all-charsets-700italic.woff2 │ ├── open-sans-v17-all-charsets-800.woff2 │ ├── open-sans-v17-all-charsets-800italic.woff2 │ ├── open-sans-v17-all-charsets-italic.woff2 │ ├── open-sans-v17-all-charsets-regular.woff2 │ └── source-code-pro-v11-all-charsets-500.woff2 ├── functions.html ├── generics.html ├── getting-started.html ├── glossary.html ├── guessing-game.html ├── highlight.css ├── highlight.js ├── if-let.html ├── if.html ├── index.html ├── inline-assembly.html ├── intrinsics.html ├── iterators.html ├── lang-items.html ├── learn-rust.html ├── lifetimes.html ├── loops.html ├── macros.html ├── mark.min.js ├── match.html ├── method-syntax.html ├── mode-rust.js ├── mutability.html ├── nightly-rust.html ├── no-stdlib.html ├── operators-and-overloading.html ├── ownership.html ├── patterns.html ├── primitive-types.html ├── print.html ├── raw-pointers.html ├── references-and-borrowing.html ├── release-channels.html ├── rust-inside-other-languages.html ├── searcher.js ├── searchindex.js ├── searchindex.json ├── slice-patterns.html ├── strings.html ├── structs.html ├── syntax-and-semantics.html ├── syntax-index.html ├── testing.html ├── the-stack-and-the-heap.html ├── theme-dawn.js ├── theme-tomorrow_night.js ├── theme │ └── first-edition.css ├── tomorrow-night.css ├── trait-objects.html ├── traits.html ├── type-aliases.html ├── ufcs.html ├── unsafe.html ├── unsized-types.html ├── using-rust-without-the-standard-library.html ├── variable-bindings.html └── vectors.html ├── script ├── build.sh ├── check.py ├── check_captions.sh ├── check_stray_quotes.sh ├── convert-epub.sh ├── convert-mobi.sh ├── convert-pdf.sh ├── convert.sh ├── deploy.sh ├── fix.py ├── install_calibre.sh ├── install_rustbook.sh ├── replace_quotation_marks.sh └── replace_quotation_marks_en.sh ├── src ├── INTRODUCTION.md ├── SUMMARY.md ├── advanced-linking.md ├── associated-constants.md ├── associated-types.md ├── attributes.md ├── benchmark-tests.md ├── bibliography.md ├── borrow-and-asref.md ├── box-syntax-and-patterns.md ├── casting-between-types.md ├── choosing-your-guarantees.md ├── closures.md ├── comments.md ├── compiler-plugins.md ├── concurrency.md ├── conditional-compilation.md ├── const-and-static.md ├── crates-and-modules.md ├── custom-allocators.md ├── deref-coercions.md ├── dining-philosophers.md ├── documentation.md ├── drop.md ├── effective-rust.md ├── enums.md ├── error-handling.md ├── ffi.md ├── functions.md ├── generics.md ├── getting-started.md ├── glossary.md ├── guessing-game.md ├── if-let.md ├── if.md ├── inline-assembly.md ├── intrinsics.md ├── iterators.md ├── lang-items.md ├── learn-rust.md ├── lifetimes.md ├── loops.md ├── macros.md ├── match.md ├── method-syntax.md ├── mutability.md ├── nightly-rust.md ├── no-stdlib.md ├── operators-and-overloading.md ├── ownership.md ├── patterns.md ├── primitive-types.md ├── raw-pointers.md ├── references-and-borrowing.md ├── release-channels.md ├── rust-inside-other-languages.md ├── slice-patterns.md ├── strings.md ├── structs.md ├── syntax-and-semantics.md ├── syntax-index.md ├── testing.md ├── the-stack-and-the-heap.md ├── trait-objects.md ├── traits.md ├── type-aliases.md ├── ufcs.md ├── unsafe.md ├── unsized-types.md ├── using-rust-without-the-standard-library.md ├── variable-bindings.md └── vectors.md ├── static └── css │ ├── rust-book-pdf.css │ ├── rust-book-pdf.min.css │ ├── rust-book.css │ ├── rust-book.min.css │ └── rust.css └── theme ├── first-edition.css ├── header.hbs └── index.hbs /AUTHORS.md: -------------------------------------------------------------------------------- 1 | * [dieu](https://github.com/dieu) 2 | * [funkill](https://github.com/funkill) 3 | * [hhblaze](https://github.com/hhblaze) 4 | * [ithamsteri](https://github.com/ithamsteri) 5 | * [jiumx60rus](https://github.com/jiumx60rus) 6 | * [kgv](https://github.com/kgv) 7 | * [mkpankov](https://github.com/mkpankov) 8 | * [rastopyr](https://github.com/rastopyr) 9 | * [suhr](https://github.com/suhr) 10 | * [vessd](https://github.com/vessd) 11 | * [vkibalyuk](https://github.com/VKibalyuk) 12 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Участие в проекте 2 | 3 | Спасибо за интерес к нашему проекту. Есть много способов помочь, и все виды 4 | помощи ценны для нас. 5 | 6 | ## Расскажите о нас 7 | 8 | Многие люди знают английский на достаточном уровне, но всё же испытывают 9 | трудности при чтении больших книг в оригинале. Поэтому рассказывайте о нас 10 | друзьям и коллегам - это полезнее, чем кажется. 11 | 12 | ## Опечатки и стиль 13 | 14 | Следующий простой способ помочь - исправлять опечатки, которые вы встречаете по 15 | мере чтения. Усилия, которые вы затратите на исправление опечатки, примерно 16 | равны усилиям на создание задачи об опечатке - и при этом снимают с нас часть 17 | работы. 18 | 19 | Это проще, чем кажется - любой файл в репозитории можно редактировать прямо в 20 | браузере. При этом GitHub сам создаст ветку и сделает Pull Request. Просто 21 | кликните по файлу в списке в веб-интерфейсе GitHub, а затем нажмите на маленькую 22 | иконку карандаша. 23 | 24 | Отредактируйте файл, введите сообщение коммита - и готово. Pull Request создан и 25 | мы уведомлены о нём. 26 | 27 | Уже созданные задачи на исправление опечаток имеют соответствующую 28 | [метку][typos] в репозитории. 29 | 30 | [typos]: https://github.com/ruRust/rust_book_ru/labels/%D0%BE%D0%BF%D0%B5%D1%87%D0%B0%D1%82%D0%BA%D0%B0 31 | 32 | Корявые фразы, калька с английского, непонятные места подлежат исправлению тем 33 | же способом. У них также есть [метка][style]. 34 | 35 | [style]: https://github.com/ruRust/rust_book_ru/labels/%D1%81%D1%82%D0%B8%D0%BB%D1%8C 36 | 37 | ## Перевод 38 | 39 | Вы можете поучаствовать в переводе ещё не переведённых частей или помочь 40 | привести перевод в соответствие с оригиналом. 41 | 42 | Для этого смотрите задачи с [меткой][content] "тип: содержимое". 43 | 44 | [content]: https://github.com/ruRust/rust_book_ru/labels/%D1%82%D0%B8%D0%BF%3A%20%D1%81%D0%BE%D0%B4%D0%B5%D1%80%D0%B6%D0%B8%D0%BC%D0%BE%D0%B5 45 | 46 | Эти задачи, как правило, можно выполнять, вообще не собирая проект локально - 47 | Markdown достаточно предсказуем, чтобы редактировать текст книг без локальной 48 | проверки. 49 | 50 | ## Инфраструктура 51 | 52 | Есть определённые инфраструктурные задачи. Они, как правило, требуют 53 | программирования - или, по крайней мере, редактирования каких-то 54 | конфигурационных файлов и скриптов. 55 | 56 | Это задачи с [меткой][infra] "тип: инфраструктура". 57 | 58 | [infra]: https://github.com/ruRust/rust_book_ru/labels/%D1%82%D0%B8%D0%BF%3A%20%D0%B8%D0%BD%D1%84%D1%80%D0%B0%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0 59 | 60 | ## Pull Request'ы 61 | 62 | При создании и рецензировании Pull Request'ов следует придерживаться трёх 63 | правил: 64 | 65 | 1. Понятно описывайте свою работу. Это значит, что сообщения коммитов и Pull 66 | Request'а должны быть в правильном формате и на русском языке. 67 | 2. Адекватно реагируйте на замечания в процессе рецензирования. Рецензирование - 68 | способ поддержания качества нашего проекта. 69 | 3. Не забивайте на обновление PR по результатам рецензирования. Вы лучше всего 70 | разбираетесь в том, что вы сделали, и кроме вас никто не займётся вливанием 71 | ваших правок в проект. 72 | 73 | Подробнее о процессе и правилах читайте [здесь][contrib]. 74 | 75 | [contrib]: https://rustycrate.ru/%D1%80%D1%83%D0%BA%D0%BE%D0%B2%D0%BE%D0%B4%D1%81%D1%82%D0%B2%D0%B0/2016/03/07/contributing.html 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### Репозиторий перехал 2 | 3 | Дальнейшее развитие идёт тут: https://github.com/rust-lang-ru/book 4 | 5 | Через некоторое время этот репозиторий будет удалён. 6 | -------------------------------------------------------------------------------- /README.rev.template.md: -------------------------------------------------------------------------------- 1 | 2 | ## Ревизия исходного кода данной версии книги 3 | 4 | `` 5 | -------------------------------------------------------------------------------- /book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["funkill2"] 3 | language = "ru" 4 | multilingual = false 5 | src = "src" 6 | title = "Язык программирования Rust" 7 | 8 | [output.html] 9 | google-analytics="UA-142155799-10" 10 | additional-css = ["theme/first-edition.css"] 11 | 12 | [output.html.playpen] 13 | editable = true 14 | editor = "ace" 15 | -------------------------------------------------------------------------------- /cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/cover.jpg -------------------------------------------------------------------------------- /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | This file makes sure that Github Pages doesn't process mdBook's output. 2 | -------------------------------------------------------------------------------- /docs/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

Document not found (404)

61 |

This URL is invalid, sorry. Please use the navigation bar or search to continue.

62 | 63 |
64 |
65 |
66 |
67 | 68 | 69 | -------------------------------------------------------------------------------- /docs/FontAwesome/fonts/FontAwesome.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/FontAwesome/fonts/FontAwesome.ttf -------------------------------------------------------------------------------- /docs/FontAwesome/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/FontAwesome/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /docs/FontAwesome/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/FontAwesome/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /docs/FontAwesome/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/FontAwesome/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /docs/FontAwesome/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/FontAwesome/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /docs/associated-constants.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Ассоциированные константы - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Ассоциированные константы

61 |

С включенной возможностью associated_consts вы можете определить константы 62 | вроде этой:

63 |
#![feature(associated_consts)]
 64 | 
 65 | trait Foo {
 66 |     const ID: i32;
 67 | }
 68 | 
 69 | impl Foo for i32 {
 70 |     const ID: i32 = 1;
 71 | }
 72 | 
 73 | fn main() {
 74 |     assert_eq!(1, i32::ID);
 75 | }
 76 | 
77 |

Любая реализация Foo должна будет определить ID. Без этого определения:

78 |
#![feature(associated_consts)]
 79 | 
 80 | trait Foo {
 81 |     const ID: i32;
 82 | }
 83 | 
 84 | impl Foo for i32 {
 85 | }
 86 | 
87 |

выдаст ошибку

88 |
error: not all trait items implemented, missing: `ID` [E0046]
 89 |      impl Foo for i32 {
 90 |      }
 91 | 
92 |

Также может быть реализовано значение по умолчанию:

93 |
#![feature(associated_consts)]
 94 | 
 95 | trait Foo {
 96 |     const ID: i32 = 1;
 97 | }
 98 | 
 99 | impl Foo for i32 {
100 | }
101 | 
102 | impl Foo for i64 {
103 |     const ID: i32 = 5;
104 | }
105 | 
106 | fn main() {
107 |     assert_eq!(1, i32::ID);
108 |     assert_eq!(5, i64::ID);
109 | }
110 | 
111 |

Как вы можете видеть, при реализации Foo, можно оставить константу 112 | неопределенной, как в случае для i32. Тогда будет использовано значение по 113 | умолчанию. Но также можно и добавить собственное определение, как в случае для 114 | i64.

115 |

Ассоциированные константы могут быть ассоциированы не только с типажом. Это 116 | также прекрасно работает и с блоком impl для struct:

117 |

118 | #![allow(unused)]
119 | #![feature(associated_consts)]
120 | 
121 | fn main() {
122 | struct Foo;
123 | 
124 | impl Foo {
125 |     pub const FOO: u32 = 3;
126 | }
127 | }
128 | 
129 | 130 |
131 |
132 |
133 |
134 | 135 | 136 | -------------------------------------------------------------------------------- /docs/attributes.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Атрибуты - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Атрибуты

61 |

В Rust объявления могут быть аннотированы с помощью «атрибутов». Они выглядят 62 | так:

63 |

 64 | #![allow(unused)]
 65 | fn main() {
 66 | #[test]
 67 | fn foo() {}
 68 | }
 69 | 
70 |

или так:

71 |

 72 | #![allow(unused)]
 73 | fn main() {
 74 | mod foo {
 75 | #![test]
 76 | }
 77 | }
 78 | 
79 |

Разница между ними состоит в символе !, который изменяет его поведение, 80 | определяющее к какому элементу применяется атрибут:

81 |
#[foo]
 82 | struct Foo;
 83 | 
 84 | mod bar {
 85 |     #![bar]
 86 | }
 87 | 
88 |

Атрибут #[foo] относится к следующему за ним элементу, который является 89 | объявлением struct. Атрибут #![bar] относится к элементу охватывающему его, 90 | который является объявлением mod. В остальном они одинаковы. Оба каким-то 91 | образом изменяют значение элемента, к которому они прикреплены.

92 |

Например, рассмотрим такую функцию:

93 |

 94 | #![allow(unused)]
 95 | fn main() {
 96 | #[test]
 97 | fn check() {
 98 |     assert_eq!(2, 1 + 1);
 99 | }
100 | }
101 | 
102 |

Функция помечена как #[test]. Это означает, что она особенная: эта функция 103 | будет выполняться при запуске тестов. При компиляции, как правило, она 104 | не будет включена. Теперь эта функция является функцией тестирования.

105 |

Атрибуты также могут иметь дополнительные данные:

106 |

107 | #![allow(unused)]
108 | fn main() {
109 | #[inline(always)]
110 | fn super_fast_fn() {
111 | }
112 | }
113 | 
114 |

Или даже ключи и значения:

115 |

116 | #![allow(unused)]
117 | fn main() {
118 | #[cfg(target_os = "macos")]
119 | mod macos_only {
120 | }
121 | }
122 | 
123 |

Атрибуты в Rust используются для ряда различных вещей. Вот ссылка 124 | на полный список атрибутов. В настоящее время вы не можете создавать свои 125 | собственные атрибуты, компилятор Rust определяет их.

126 | 127 |
128 |
129 |
130 |
131 | 132 | 133 | -------------------------------------------------------------------------------- /docs/ayu-highlight.css: -------------------------------------------------------------------------------- 1 | /* 2 | Based off of the Ayu theme 3 | Original by Dempfi (https://github.com/dempfi/ayu) 4 | */ 5 | 6 | .hljs { 7 | display: block; 8 | overflow-x: auto; 9 | background: #191f26; 10 | color: #e6e1cf; 11 | padding: 0.5em; 12 | } 13 | 14 | .hljs-comment, 15 | .hljs-quote { 16 | color: #5c6773; 17 | font-style: italic; 18 | } 19 | 20 | .hljs-variable, 21 | .hljs-template-variable, 22 | .hljs-attribute, 23 | .hljs-attr, 24 | .hljs-regexp, 25 | .hljs-link, 26 | .hljs-selector-id, 27 | .hljs-selector-class { 28 | color: #ff7733; 29 | } 30 | 31 | .hljs-number, 32 | .hljs-meta, 33 | .hljs-builtin-name, 34 | .hljs-literal, 35 | .hljs-type, 36 | .hljs-params { 37 | color: #ffee99; 38 | } 39 | 40 | .hljs-string, 41 | .hljs-bullet { 42 | color: #b8cc52; 43 | } 44 | 45 | .hljs-title, 46 | .hljs-built_in, 47 | .hljs-section { 48 | color: #ffb454; 49 | } 50 | 51 | .hljs-keyword, 52 | .hljs-selector-tag, 53 | .hljs-symbol { 54 | color: #ff7733; 55 | } 56 | 57 | .hljs-name { 58 | color: #36a3d9; 59 | } 60 | 61 | .hljs-tag { 62 | color: #00568d; 63 | } 64 | 65 | .hljs-emphasis { 66 | font-style: italic; 67 | } 68 | 69 | .hljs-strong { 70 | font-weight: bold; 71 | } 72 | 73 | .hljs-addition { 74 | color: #91b362; 75 | } 76 | 77 | .hljs-deletion { 78 | color: #d96c75; 79 | } 80 | -------------------------------------------------------------------------------- /docs/comments.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Комментарии - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Комментарии

61 |

Теперь, когда у нас есть несколько функций, неплохо бы узнать о комментариях. 62 | Комментарии — это заметки, которые вы оставляете для других программистов, чтобы 63 | помочь объяснить некоторые вещи в вашем коде. Компилятор в основном игнорирует 64 | их («в основном», потому что есть документирующие комментарии и примеры в 65 | документации).

66 |

В Rust есть два вида комментариев: строчные комментарии и doc-комментарии.

67 |

 68 | #![allow(unused)]
 69 | fn main() {
 70 | // Строчные комментарии — это всё что угодно после '//' и до конца строки.
 71 | 
 72 | let x = 5; // это тоже строчный комментарий.
 73 | 
 74 | // Если у вас длинное объяснение для чего-либо, вы можете расположить строчные
 75 | // комментарии один за другим. Поместите пробел между '//' и вашим комментарием,
 76 | // так как это более читаемо.
 77 | }
 78 | 
79 |

Другое применение комментария — это doc-комментарий. Doc-комментарий использует 80 | /// вместо //, и поддерживает Markdown-разметку внутри:

81 |

 82 | #![allow(unused)]
 83 | fn main() {
 84 | /// Прибавляем единицу к заданному числу.
 85 | ///
 86 | /// # Examples
 87 | ///
 88 | /// ```
 89 | /// let five = 5;
 90 | ///
 91 | /// assert_eq!(6, add_one(5));
 92 | /// ```
 93 | fn add_one(x: i32) -> i32 {
 94 |     x + 1
 95 | }
 96 | }
 97 | 
98 |

При написании doc-комментария очень полезно добавлять разделы для аргументов, 99 | возвращаемых значений и привести некоторые примеры использования. Заметьте, что 100 | здесь мы использовали новый макрос: assert_eq!. Он сравнивает два значения и 101 | вызывает panic!, если они не равны. Для документации такие примеры очень 102 | полезны. Так же есть и другой макрос, assert!, который вызывает panic! когда 103 | значение равно false.

104 |

Вы можете использовать rustdoc для генерации HTML- 105 | документации из этих doc-комментариев, а так же запуска кода из примеров как 106 | тестов.

107 | 108 |
109 |
110 |
111 |
112 | 113 | 114 | -------------------------------------------------------------------------------- /docs/css/general.css: -------------------------------------------------------------------------------- 1 | /* Base styles and content styles */ 2 | 3 | @import 'variables.css'; 4 | 5 | :root { 6 | /* Browser default font-size is 16px, this way 1 rem = 10px */ 7 | font-size: 62.5%; 8 | } 9 | 10 | html { 11 | font-family: "Open Sans", sans-serif; 12 | color: var(--fg); 13 | background-color: var(--bg); 14 | text-size-adjust: none; 15 | } 16 | 17 | body { 18 | margin: 0; 19 | font-size: 1.6rem; 20 | overflow-x: hidden; 21 | } 22 | 23 | code { 24 | font-family: "Source Code Pro", Consolas, "Ubuntu Mono", Menlo, "DejaVu Sans Mono", monospace, monospace !important; 25 | font-size: 0.875em; /* please adjust the ace font size accordingly in editor.js */ 26 | } 27 | 28 | /* Don't change font size in headers. */ 29 | h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { 30 | font-size: unset; 31 | } 32 | 33 | .left { float: left; } 34 | .right { float: right; } 35 | .boring { opacity: 0.6; } 36 | .hide-boring .boring { display: none; } 37 | .hidden { display: none !important; } 38 | 39 | h2, h3 { margin-top: 2.5em; } 40 | h4, h5 { margin-top: 2em; } 41 | 42 | .header + .header h3, 43 | .header + .header h4, 44 | .header + .header h5 { 45 | margin-top: 1em; 46 | } 47 | 48 | h1 a.header:target::before, 49 | h2 a.header:target::before, 50 | h3 a.header:target::before, 51 | h4 a.header:target::before { 52 | display: inline-block; 53 | content: "»"; 54 | margin-left: -30px; 55 | width: 30px; 56 | } 57 | 58 | h1 a.header:target, 59 | h2 a.header:target, 60 | h3 a.header:target, 61 | h4 a.header:target { 62 | scroll-margin-top: calc(var(--menu-bar-height) + 0.5em); 63 | } 64 | 65 | .page { 66 | outline: 0; 67 | padding: 0 var(--page-padding); 68 | margin-top: calc(0px - var(--menu-bar-height)); /* Compensate for the #menu-bar-hover-placeholder */ 69 | } 70 | .page-wrapper { 71 | box-sizing: border-box; 72 | } 73 | .js:not(.sidebar-resizing) .page-wrapper { 74 | transition: margin-left 0.3s ease, transform 0.3s ease; /* Animation: slide away */ 75 | } 76 | 77 | .content { 78 | overflow-y: auto; 79 | padding: 0 15px; 80 | padding-bottom: 50px; 81 | } 82 | .content main { 83 | margin-left: auto; 84 | margin-right: auto; 85 | max-width: var(--content-max-width); 86 | } 87 | .content p { line-height: 1.45em; } 88 | .content ol { line-height: 1.45em; } 89 | .content ul { line-height: 1.45em; } 90 | .content a { text-decoration: none; } 91 | .content a:hover { text-decoration: underline; } 92 | .content img { max-width: 100%; } 93 | .content .header:link, 94 | .content .header:visited { 95 | color: var(--fg); 96 | } 97 | .content .header:link, 98 | .content .header:visited:hover { 99 | text-decoration: none; 100 | } 101 | 102 | table { 103 | margin: 0 auto; 104 | border-collapse: collapse; 105 | } 106 | table td { 107 | padding: 3px 20px; 108 | border: 1px var(--table-border-color) solid; 109 | } 110 | table thead { 111 | background: var(--table-header-bg); 112 | } 113 | table thead td { 114 | font-weight: 700; 115 | border: none; 116 | } 117 | table thead th { 118 | padding: 3px 20px; 119 | } 120 | table thead tr { 121 | border: 1px var(--table-header-bg) solid; 122 | } 123 | /* Alternate background colors for rows */ 124 | table tbody tr:nth-child(2n) { 125 | background: var(--table-alternate-bg); 126 | } 127 | 128 | 129 | blockquote { 130 | margin: 20px 0; 131 | padding: 0 20px; 132 | color: var(--fg); 133 | background-color: var(--quote-bg); 134 | border-top: .1em solid var(--quote-border); 135 | border-bottom: .1em solid var(--quote-border); 136 | } 137 | 138 | 139 | :not(.footnote-definition) + .footnote-definition, 140 | .footnote-definition + :not(.footnote-definition) { 141 | margin-top: 2em; 142 | } 143 | .footnote-definition { 144 | font-size: 0.9em; 145 | margin: 0.5em 0; 146 | } 147 | .footnote-definition p { 148 | display: inline; 149 | } 150 | 151 | .tooltiptext { 152 | position: absolute; 153 | visibility: hidden; 154 | color: #fff; 155 | background-color: #333; 156 | transform: translateX(-50%); /* Center by moving tooltip 50% of its width left */ 157 | left: -8px; /* Half of the width of the icon */ 158 | top: -35px; 159 | font-size: 0.8em; 160 | text-align: center; 161 | border-radius: 6px; 162 | padding: 5px 8px; 163 | margin: 5px; 164 | z-index: 1000; 165 | } 166 | .tooltipped .tooltiptext { 167 | visibility: visible; 168 | } 169 | 170 | .chapter li.part-title { 171 | color: var(--sidebar-fg); 172 | margin: 5px 0px; 173 | font-weight: bold; 174 | } 175 | -------------------------------------------------------------------------------- /docs/css/print.css: -------------------------------------------------------------------------------- 1 | 2 | #sidebar, 3 | #menu-bar, 4 | .nav-chapters, 5 | .mobile-nav-chapters { 6 | display: none; 7 | } 8 | 9 | #page-wrapper.page-wrapper { 10 | transform: none; 11 | margin-left: 0px; 12 | overflow-y: initial; 13 | } 14 | 15 | #content { 16 | max-width: none; 17 | margin: 0; 18 | padding: 0; 19 | } 20 | 21 | .page { 22 | overflow-y: initial; 23 | } 24 | 25 | code { 26 | background-color: #666666; 27 | border-radius: 5px; 28 | 29 | /* Force background to be printed in Chrome */ 30 | -webkit-print-color-adjust: exact; 31 | } 32 | 33 | pre > .buttons { 34 | z-index: 2; 35 | } 36 | 37 | a, a:visited, a:active, a:hover { 38 | color: #4183c4; 39 | text-decoration: none; 40 | } 41 | 42 | h1, h2, h3, h4, h5, h6 { 43 | page-break-inside: avoid; 44 | page-break-after: avoid; 45 | } 46 | 47 | pre, code { 48 | page-break-inside: avoid; 49 | white-space: pre-wrap; 50 | } 51 | 52 | .fa { 53 | display: none !important; 54 | } 55 | -------------------------------------------------------------------------------- /docs/drop.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Типаж Drop - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Типаж Drop (сброс)

61 |

Мы обсудили типажи. Теперь давайте поговорим о конкретном типаже, 62 | предоставляемом стандартной библиотекой Rust. Этот типаж — Drop 63 | (сброс) — позволяет выполнить некоторый код, когда значение выходит из области 64 | видимости. Например:

65 |
struct HasDrop;
 66 | 
 67 | impl Drop for HasDrop {
 68 |     fn drop(&mut self) {
 69 |         println!("Сбрасываем!");
 70 |     }
 71 | }
 72 | 
 73 | fn main() {
 74 |     let x = HasDrop;
 75 | 
 76 |     // сделаем что-то
 77 | 
 78 | } // тут x выходит из области видимости
 79 | 
80 |

Когда x выходит из области видимости в конце main(), исполнится код 81 | реализации типажа Drop. У него один метод, который тоже называется drop(). 82 | Он принимает изменяемую ссылку на себя (self).

83 |

Вот и всё! Работа Drop достаточно проста, но есть несколько 84 | тонкостей. Например, значения сбрасываются в порядке, обратном порядку их 85 | объявления. Вот ещё пример:

86 |
struct Firework {
 87 |     strength: i32,
 88 | }
 89 | 
 90 | impl Drop for Firework {
 91 |     fn drop(&mut self) {
 92 |         println!("БАБАХ силой {}!!!", self.strength);
 93 |     }
 94 | }
 95 | 
 96 | fn main() {
 97 |     let firecracker = Firework { strength: 1 };
 98 |     let tnt = Firework { strength: 100 };
 99 | }
100 | 
101 |

Этот код выведет следующее:

102 |
БАБАХ силой 100!!!
103 | БАБАХ силой 1!!!
104 | 
105 |

Сначала взрывается тринитротолуоловая бомба (tnt), потому что она была 106 | объявлена последней. За ней взрывается шутиха (firecracker). Первым вошёл, 107 | последним вышел.

108 |

Так зачем нужен Drop? Часто Drop используют, чтобы освободить ресурсы, 109 | представленные структурой (struct). Например, счётчик ссылок Arc<T> 110 | уменьшает число активных ссылок в drop(), и когда оно достигает нуля, 111 | освобождает хранимое значение.

112 | 113 |
114 |
115 |
116 |
117 | 118 | 119 | -------------------------------------------------------------------------------- /docs/editor.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | window.editors = []; 3 | (function(editors) { 4 | if (typeof(ace) === 'undefined' || !ace) { 5 | return; 6 | } 7 | 8 | Array.from(document.querySelectorAll('.editable')).forEach(function(editable) { 9 | let display_line_numbers = window.playground_line_numbers || false; 10 | 11 | let editor = ace.edit(editable); 12 | editor.setOptions({ 13 | highlightActiveLine: false, 14 | showPrintMargin: false, 15 | showLineNumbers: display_line_numbers, 16 | showGutter: display_line_numbers, 17 | maxLines: Infinity, 18 | fontSize: "0.875em" // please adjust the font size of the code in general.css 19 | }); 20 | 21 | editor.$blockScrolling = Infinity; 22 | 23 | editor.getSession().setMode("ace/mode/rust"); 24 | 25 | editor.originalCode = editor.getValue(); 26 | 27 | editors.push(editor); 28 | }); 29 | })(window.editors); 30 | -------------------------------------------------------------------------------- /docs/effective-rust.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Эффективное использование Rust - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Эффективное использование Rust

61 |

Итак, вы узнали, как писать код на Rust. Но есть разница между написанием 62 | какого-то кода на Rust и написанием хорошего кода на Rust.

63 |

Этот раздел состоит из относительно самостоятельных уроков, которые показывают, 64 | как повысить уровень вашего кода на Rust. В нем представлены общие шаблоны и 65 | стандартные функции библиотеки. Главы в этом разделе могут быть прочитаны в 66 | любом порядке по вашему выбору.

67 | 68 |
69 |
70 |
71 |
72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/favicon.png -------------------------------------------------------------------------------- /docs/favicon.svg: -------------------------------------------------------------------------------- 1 | 2 | 7 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /docs/fonts/SOURCE-CODE-PRO-LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. 2 | 3 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 4 | This license is copied below, and is also available with a FAQ at: 5 | http://scripts.sil.org/OFL 6 | 7 | 8 | ----------------------------------------------------------- 9 | SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 10 | ----------------------------------------------------------- 11 | 12 | PREAMBLE 13 | The goals of the Open Font License (OFL) are to stimulate worldwide 14 | development of collaborative font projects, to support the font creation 15 | efforts of academic and linguistic communities, and to provide a free and 16 | open framework in which fonts may be shared and improved in partnership 17 | with others. 18 | 19 | The OFL allows the licensed fonts to be used, studied, modified and 20 | redistributed freely as long as they are not sold by themselves. The 21 | fonts, including any derivative works, can be bundled, embedded, 22 | redistributed and/or sold with any software provided that any reserved 23 | names are not used by derivative works. The fonts and derivatives, 24 | however, cannot be released under any other type of license. The 25 | requirement for fonts to remain under this license does not apply 26 | to any document created using the fonts or their derivatives. 27 | 28 | DEFINITIONS 29 | "Font Software" refers to the set of files released by the Copyright 30 | Holder(s) under this license and clearly marked as such. This may 31 | include source files, build scripts and documentation. 32 | 33 | "Reserved Font Name" refers to any names specified as such after the 34 | copyright statement(s). 35 | 36 | "Original Version" refers to the collection of Font Software components as 37 | distributed by the Copyright Holder(s). 38 | 39 | "Modified Version" refers to any derivative made by adding to, deleting, 40 | or substituting -- in part or in whole -- any of the components of the 41 | Original Version, by changing formats or by porting the Font Software to a 42 | new environment. 43 | 44 | "Author" refers to any designer, engineer, programmer, technical 45 | writer or other person who contributed to the Font Software. 46 | 47 | PERMISSION & CONDITIONS 48 | Permission is hereby granted, free of charge, to any person obtaining 49 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 50 | redistribute, and sell modified and unmodified copies of the Font 51 | Software, subject to the following conditions: 52 | 53 | 1) Neither the Font Software nor any of its individual components, 54 | in Original or Modified Versions, may be sold by itself. 55 | 56 | 2) Original or Modified Versions of the Font Software may be bundled, 57 | redistributed and/or sold with any software, provided that each copy 58 | contains the above copyright notice and this license. These can be 59 | included either as stand-alone text files, human-readable headers or 60 | in the appropriate machine-readable metadata fields within text or 61 | binary files as long as those fields can be easily viewed by the user. 62 | 63 | 3) No Modified Version of the Font Software may use the Reserved Font 64 | Name(s) unless explicit written permission is granted by the corresponding 65 | Copyright Holder. This restriction only applies to the primary font name as 66 | presented to the users. 67 | 68 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 69 | Software shall not be used to promote, endorse or advertise any 70 | Modified Version, except to acknowledge the contribution(s) of the 71 | Copyright Holder(s) and the Author(s) or with their explicit written 72 | permission. 73 | 74 | 5) The Font Software, modified or unmodified, in part or in whole, 75 | must be distributed entirely under this license, and must not be 76 | distributed under any other license. The requirement for fonts to 77 | remain under this license does not apply to any document created 78 | using the Font Software. 79 | 80 | TERMINATION 81 | This license becomes null and void if any of the above conditions are 82 | not met. 83 | 84 | DISCLAIMER 85 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 86 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 87 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 88 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 89 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 90 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 91 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 92 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 93 | OTHER DEALINGS IN THE FONT SOFTWARE. 94 | -------------------------------------------------------------------------------- /docs/fonts/fonts.css: -------------------------------------------------------------------------------- 1 | /* Open Sans is licensed under the Apache License, Version 2.0. See http://www.apache.org/licenses/LICENSE-2.0 */ 2 | /* Source Code Pro is under the Open Font License. See https://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL */ 3 | 4 | /* open-sans-300 - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 5 | @font-face { 6 | font-family: 'Open Sans'; 7 | font-style: normal; 8 | font-weight: 300; 9 | src: local('Open Sans Light'), local('OpenSans-Light'), 10 | url('open-sans-v17-all-charsets-300.woff2') format('woff2'); 11 | } 12 | 13 | /* open-sans-300italic - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 14 | @font-face { 15 | font-family: 'Open Sans'; 16 | font-style: italic; 17 | font-weight: 300; 18 | src: local('Open Sans Light Italic'), local('OpenSans-LightItalic'), 19 | url('open-sans-v17-all-charsets-300italic.woff2') format('woff2'); 20 | } 21 | 22 | /* open-sans-regular - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 23 | @font-face { 24 | font-family: 'Open Sans'; 25 | font-style: normal; 26 | font-weight: 400; 27 | src: local('Open Sans Regular'), local('OpenSans-Regular'), 28 | url('open-sans-v17-all-charsets-regular.woff2') format('woff2'); 29 | } 30 | 31 | /* open-sans-italic - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 32 | @font-face { 33 | font-family: 'Open Sans'; 34 | font-style: italic; 35 | font-weight: 400; 36 | src: local('Open Sans Italic'), local('OpenSans-Italic'), 37 | url('open-sans-v17-all-charsets-italic.woff2') format('woff2'); 38 | } 39 | 40 | /* open-sans-600 - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 41 | @font-face { 42 | font-family: 'Open Sans'; 43 | font-style: normal; 44 | font-weight: 600; 45 | src: local('Open Sans SemiBold'), local('OpenSans-SemiBold'), 46 | url('open-sans-v17-all-charsets-600.woff2') format('woff2'); 47 | } 48 | 49 | /* open-sans-600italic - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 50 | @font-face { 51 | font-family: 'Open Sans'; 52 | font-style: italic; 53 | font-weight: 600; 54 | src: local('Open Sans SemiBold Italic'), local('OpenSans-SemiBoldItalic'), 55 | url('open-sans-v17-all-charsets-600italic.woff2') format('woff2'); 56 | } 57 | 58 | /* open-sans-700 - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 59 | @font-face { 60 | font-family: 'Open Sans'; 61 | font-style: normal; 62 | font-weight: 700; 63 | src: local('Open Sans Bold'), local('OpenSans-Bold'), 64 | url('open-sans-v17-all-charsets-700.woff2') format('woff2'); 65 | } 66 | 67 | /* open-sans-700italic - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 68 | @font-face { 69 | font-family: 'Open Sans'; 70 | font-style: italic; 71 | font-weight: 700; 72 | src: local('Open Sans Bold Italic'), local('OpenSans-BoldItalic'), 73 | url('open-sans-v17-all-charsets-700italic.woff2') format('woff2'); 74 | } 75 | 76 | /* open-sans-800 - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 77 | @font-face { 78 | font-family: 'Open Sans'; 79 | font-style: normal; 80 | font-weight: 800; 81 | src: local('Open Sans ExtraBold'), local('OpenSans-ExtraBold'), 82 | url('open-sans-v17-all-charsets-800.woff2') format('woff2'); 83 | } 84 | 85 | /* open-sans-800italic - latin_vietnamese_latin-ext_greek-ext_greek_cyrillic-ext_cyrillic */ 86 | @font-face { 87 | font-family: 'Open Sans'; 88 | font-style: italic; 89 | font-weight: 800; 90 | src: local('Open Sans ExtraBold Italic'), local('OpenSans-ExtraBoldItalic'), 91 | url('open-sans-v17-all-charsets-800italic.woff2') format('woff2'); 92 | } 93 | 94 | /* source-code-pro-500 - latin_vietnamese_latin-ext_greek_cyrillic-ext_cyrillic */ 95 | @font-face { 96 | font-family: 'Source Code Pro'; 97 | font-style: normal; 98 | font-weight: 500; 99 | src: url('source-code-pro-v11-all-charsets-500.woff2') format('woff2'); 100 | } 101 | -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-300.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-300.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-300italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-300italic.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-600.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-600.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-600italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-600italic.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-700.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-700.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-700italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-700italic.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-800.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-800.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-800italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-800italic.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-italic.woff2 -------------------------------------------------------------------------------- /docs/fonts/open-sans-v17-all-charsets-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/open-sans-v17-all-charsets-regular.woff2 -------------------------------------------------------------------------------- /docs/fonts/source-code-pro-v11-all-charsets-500.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ruRust/rust_book_ru/8684e2e75062357b10e69660fe1d9352a4a5a878/docs/fonts/source-code-pro-v11-all-charsets-500.woff2 -------------------------------------------------------------------------------- /docs/highlight.css: -------------------------------------------------------------------------------- 1 | /* Base16 Atelier Dune Light - Theme */ 2 | /* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/dune) */ 3 | /* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ 4 | 5 | /* Atelier-Dune Comment */ 6 | .hljs-comment, 7 | .hljs-quote { 8 | color: #AAA; 9 | } 10 | 11 | /* Atelier-Dune Red */ 12 | .hljs-variable, 13 | .hljs-template-variable, 14 | .hljs-attribute, 15 | .hljs-tag, 16 | .hljs-name, 17 | .hljs-regexp, 18 | .hljs-link, 19 | .hljs-name, 20 | .hljs-selector-id, 21 | .hljs-selector-class { 22 | color: #d73737; 23 | } 24 | 25 | /* Atelier-Dune Orange */ 26 | .hljs-number, 27 | .hljs-meta, 28 | .hljs-built_in, 29 | .hljs-builtin-name, 30 | .hljs-literal, 31 | .hljs-type, 32 | .hljs-params { 33 | color: #b65611; 34 | } 35 | 36 | /* Atelier-Dune Green */ 37 | .hljs-string, 38 | .hljs-symbol, 39 | .hljs-bullet { 40 | color: #60ac39; 41 | } 42 | 43 | /* Atelier-Dune Blue */ 44 | .hljs-title, 45 | .hljs-section { 46 | color: #6684e1; 47 | } 48 | 49 | /* Atelier-Dune Purple */ 50 | .hljs-keyword, 51 | .hljs-selector-tag { 52 | color: #b854d4; 53 | } 54 | 55 | .hljs { 56 | display: block; 57 | overflow-x: auto; 58 | background: #f1f1f1; 59 | color: #6e6b5e; 60 | padding: 0.5em; 61 | } 62 | 63 | .hljs-emphasis { 64 | font-style: italic; 65 | } 66 | 67 | .hljs-strong { 68 | font-weight: bold; 69 | } 70 | 71 | .hljs-addition { 72 | color: #22863a; 73 | background-color: #f0fff4; 74 | } 75 | 76 | .hljs-deletion { 77 | color: #b31d28; 78 | background-color: #ffeef0; 79 | } 80 | -------------------------------------------------------------------------------- /docs/intrinsics.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Внутренние средства - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Внутренние средства (intrinsics)

61 |
62 |

Примечание: внутренние средства всегда будут иметь нестабильный интерфейс, 63 | рекомендуется использовать стабильные интерфейсы libcore, а не внутренние 64 | напрямую.

65 |
66 |

Они импортируются как если бы они были FFI функциями, со специальным rust- intrinsic ABI. Например, если, находясь в отдельном (автономном) контексте, 67 | хочется иметь возможность transmute между типами, а также использовать 68 | эффективную арифметику указателей, то можно импортировать эти функции через 69 | объявление, такое как

70 |
#![feature(intrinsics)]
71 | fn main() {}
72 | 
73 | extern "rust-intrinsic" {
74 |     fn transmute<T, U>(x: T) -> U;
75 | 
76 |     fn offset<T>(dst: *const T, offset: isize) -> *const T;
77 | }
78 | 
79 |

Как и с любыми другими FFI функциями, их вызов всегда небезопасен и помечен как 80 | unsafe.

81 | 82 |
83 |
84 |
85 |
86 | 87 | 88 | -------------------------------------------------------------------------------- /docs/learn-rust.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Изучение Rust - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Изучение Rust

61 |

Добро пожаловать! Этот раздел книги содержит несколько глав, которые научат вас 62 | создавать проекты на Rust. Вы также получите поверхностное представление о языке

63 |
    64 |
  • мы не будем сильно углубляться в детали.
  • 65 |
66 |

Если вы хотите более основательно изучить язык, читайте раздел 67 | «Синтаксис и семантика».

68 | 69 |
70 |
71 |
72 |
73 | 74 | 75 | -------------------------------------------------------------------------------- /docs/release-channels.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Каналы сборок - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Каналы сборок

61 |

Проект Rust использует концепцию под названием «каналы сборок» для управления 62 | сборками. Важно понять этот процесс, чтобы выбрать, какую версию Rust 63 | использовать в вашем проекте.

64 |

Обзор

65 |

Есть три канала сборок Rust:

66 |
    67 |
  • Ночной (Nightly)
  • 68 |
  • Бета (Beta)
  • 69 |
  • Стабильный (Stable)
  • 70 |
71 |

Новые ночные сборки создаются раз в день. Каждые шесть недель последняя ночная 72 | сборка переводится в канал «бета». С этого момента она будет получать только 73 | исправления серьёзных ошибок. Шесть недель спустя бета сборка переводится в 74 | канал «стабильный» и становится очередной стабильной сборкой 1.x.

75 |

Этот процесс происходит параллельно. Так, каждые шесть недель, в один и тот же 76 | день, ночная сборка превращается в бета сборку, а бета сборка превращается в 77 | стабильную сборку. Это произойдёт одновременно: стабильная сборка получит версию 78 | 1.x, бета сборка получит версию 1.(x + 1)-beta, а ночная сборка станет 79 | первой версией 1.(x + 2)-nightly.

80 |

Выбор версии

81 |

Вообще говоря, если у вас нет особых причин, вы должны использовать канал 82 | стабильных сборок. Эти сборки предназначены для широкой аудитории.

83 |

Однако, в зависимости от ваших интересов к Rust, вы можете вместо этого выбрать 84 | ночную сборку. Основной компромисс заключается в следующем: при выборе канала 85 | ночных сборок, вы можете использовать неустойчивые, новые возможности Rust. Тем 86 | не менее, нестабильные возможности могут быть изменены, и поэтому любая новая 87 | ночная сборка может сломать ваш код. Если же вы выберете стабильную сборку, то 88 | не сможете использовать экспериментальные возможности, но следующий релиз Rust 89 | не вызовет существенных проблем с критическими изменениями.

90 |

Помощь экосистеме с помощью непрерывной интеграции

91 |

А что насчёт бета канала? Мы призываем всех пользователей Rust, которые 92 | используют канал стабильных сборок, также протестировать работу с использованием 93 | бета канала в их системах непрерывной интеграции. Это поможет предупредить 94 | команду в случае возникновения неожиданных регрессий.

95 |

Кроме того, тестирование работы с использованием ночного канала может выявить 96 | регрессии даже раньше, а поэтому, если вас не затруднит создание трех сборок, мы 97 | будем признательны тестированию работы с использованием всех трех каналов.

98 | 99 |
100 |
101 |
102 |
103 | 104 | 105 | -------------------------------------------------------------------------------- /docs/slice-patterns.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Шаблоны match для срезов - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Шаблоны match для срезов

61 |

Если вы хотите в качестве шаблона для сопоставления использовать срез или 62 | массив, то вы можете использовать & и активировать возможность 63 | slice_patterns:

64 |
#![feature(slice_patterns)]
 65 | 
 66 | fn main() {
 67 |     let v = vec!["match_this", "1"];
 68 | 
 69 |     match &v[..] {
 70 |         ["match_this", second] => println!("The second element is {}", second),
 71 |         _ => {},
 72 |     }
 73 | }
 74 | 
75 |

Отключаемая возможность advanced_slice_patterns позволяет использовать .., 76 | чтобы обозначить любое число элементов в шаблоне. Этот символ подстановки можно 77 | использовать в массиве один раз. Если перед .. есть идентификатор, результат 78 | среза будет связан с этим именем. Например:

79 |
#![feature(advanced_slice_patterns, slice_patterns)]
 80 | 
 81 | fn is_symmetric(list: &[u32]) -> bool {
 82 |     match list {
 83 |         [] | [_] => true,
 84 |         [x, inside.., y] if x == y => is_symmetric(inside),
 85 |         _ => false
 86 |     }
 87 | }
 88 | 
 89 | fn main() {
 90 |     let sym = &[0, 1, 4, 2, 4, 1, 0];
 91 |     assert!(is_symmetric(sym));
 92 | 
 93 |     let not_sym = &[0, 1, 7, 2, 4, 1, 0];
 94 |     assert!(!is_symmetric(not_sym));
 95 | }
 96 | 
97 | 98 |
99 |
100 |
101 |
102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/syntax-and-semantics.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Синтаксис и семантика - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Синтаксис и семантика

61 |

Эта часть разбита на небольшие главы, каждая из которых описывает определённое 62 | понятие Rust.

63 |

Если вы хотите изучить Rust «от и до», продолжайте чтение данной части по 64 | порядку - вы на верном пути!

65 |

Эти главы также являются справочником понятий, так что если при чтении другого 66 | материала вам будет что-то непонятно, вы всегда сможете найти объяснение здесь.

67 | 68 |
69 |
70 |
71 |
72 | 73 | 74 | -------------------------------------------------------------------------------- /docs/theme-dawn.js: -------------------------------------------------------------------------------- 1 | ace.define("ace/theme/dawn",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-dawn",t.cssText=".ace-dawn .ace_gutter {background: #ebebeb;color: #333}.ace-dawn .ace_print-margin {width: 1px;background: #e8e8e8}.ace-dawn {background-color: #F9F9F9;color: #080808}.ace-dawn .ace_cursor {color: #000000}.ace-dawn .ace_marker-layer .ace_selection {background: rgba(39, 95, 255, 0.30)}.ace-dawn.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #F9F9F9;}.ace-dawn .ace_marker-layer .ace_step {background: rgb(255, 255, 0)}.ace-dawn .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgba(75, 75, 126, 0.50)}.ace-dawn .ace_marker-layer .ace_active-line {background: rgba(36, 99, 180, 0.12)}.ace-dawn .ace_gutter-active-line {background-color : #dcdcdc}.ace-dawn .ace_marker-layer .ace_selected-word {border: 1px solid rgba(39, 95, 255, 0.30)}.ace-dawn .ace_invisible {color: rgba(75, 75, 126, 0.50)}.ace-dawn .ace_keyword,.ace-dawn .ace_meta {color: #794938}.ace-dawn .ace_constant,.ace-dawn .ace_constant.ace_character,.ace-dawn .ace_constant.ace_character.ace_escape,.ace-dawn .ace_constant.ace_other {color: #811F24}.ace-dawn .ace_invalid.ace_illegal {text-decoration: underline;font-style: italic;color: #F8F8F8;background-color: #B52A1D}.ace-dawn .ace_invalid.ace_deprecated {text-decoration: underline;font-style: italic;color: #B52A1D}.ace-dawn .ace_support {color: #691C97}.ace-dawn .ace_support.ace_constant {color: #B4371F}.ace-dawn .ace_fold {background-color: #794938;border-color: #080808}.ace-dawn .ace_list,.ace-dawn .ace_markup.ace_list,.ace-dawn .ace_support.ace_function {color: #693A17}.ace-dawn .ace_storage {font-style: italic;color: #A71D5D}.ace-dawn .ace_string {color: #0B6125}.ace-dawn .ace_string.ace_regexp {color: #CF5628}.ace-dawn .ace_comment {font-style: italic;color: #5A525F}.ace-dawn .ace_heading,.ace-dawn .ace_markup.ace_heading {color: #19356D}.ace-dawn .ace_variable {color: #234A97}.ace-dawn .ace_indent-guide {background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYLh/5+x/AAizA4hxNNsZAAAAAElFTkSuQmCC) right repeat-y}";var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)}); (function() { 2 | ace.require(["ace/theme/dawn"], function(m) { 3 | if (typeof module == "object" && typeof exports == "object" && module) { 4 | module.exports = m; 5 | } 6 | }); 7 | })(); 8 | -------------------------------------------------------------------------------- /docs/theme-tomorrow_night.js: -------------------------------------------------------------------------------- 1 | ace.define("ace/theme/tomorrow_night",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!0,t.cssClass="ace-tomorrow-night",t.cssText=".ace-tomorrow-night .ace_gutter {background: #25282c;color: #C5C8C6}.ace-tomorrow-night .ace_print-margin {width: 1px;background: #25282c}.ace-tomorrow-night {background-color: #1D1F21;color: #C5C8C6}.ace-tomorrow-night .ace_cursor {color: #AEAFAD}.ace-tomorrow-night .ace_marker-layer .ace_selection {background: #373B41}.ace-tomorrow-night.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px #1D1F21;}.ace-tomorrow-night .ace_marker-layer .ace_step {background: rgb(102, 82, 0)}.ace-tomorrow-night .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #4B4E55}.ace-tomorrow-night .ace_marker-layer .ace_active-line {background: #282A2E}.ace-tomorrow-night .ace_gutter-active-line {background-color: #282A2E}.ace-tomorrow-night .ace_marker-layer .ace_selected-word {border: 1px solid #373B41}.ace-tomorrow-night .ace_invisible {color: #4B4E55}.ace-tomorrow-night .ace_keyword,.ace-tomorrow-night .ace_meta,.ace-tomorrow-night .ace_storage,.ace-tomorrow-night .ace_storage.ace_type,.ace-tomorrow-night .ace_support.ace_type {color: #B294BB}.ace-tomorrow-night .ace_keyword.ace_operator {color: #8ABEB7}.ace-tomorrow-night .ace_constant.ace_character,.ace-tomorrow-night .ace_constant.ace_language,.ace-tomorrow-night .ace_constant.ace_numeric,.ace-tomorrow-night .ace_keyword.ace_other.ace_unit,.ace-tomorrow-night .ace_support.ace_constant,.ace-tomorrow-night .ace_variable.ace_parameter {color: #DE935F}.ace-tomorrow-night .ace_constant.ace_other {color: #CED1CF}.ace-tomorrow-night .ace_invalid {color: #CED2CF;background-color: #DF5F5F}.ace-tomorrow-night .ace_invalid.ace_deprecated {color: #CED2CF;background-color: #B798BF}.ace-tomorrow-night .ace_fold {background-color: #81A2BE;border-color: #C5C8C6}.ace-tomorrow-night .ace_entity.ace_name.ace_function,.ace-tomorrow-night .ace_support.ace_function,.ace-tomorrow-night .ace_variable {color: #81A2BE}.ace-tomorrow-night .ace_support.ace_class,.ace-tomorrow-night .ace_support.ace_type {color: #F0C674}.ace-tomorrow-night .ace_heading,.ace-tomorrow-night .ace_markup.ace_heading,.ace-tomorrow-night .ace_string {color: #B5BD68}.ace-tomorrow-night .ace_entity.ace_name.ace_tag,.ace-tomorrow-night .ace_entity.ace_other.ace_attribute-name,.ace-tomorrow-night .ace_meta.ace_tag,.ace-tomorrow-night .ace_string.ace_regexp,.ace-tomorrow-night .ace_variable {color: #CC6666}.ace-tomorrow-night .ace_comment {color: #969896}.ace-tomorrow-night .ace_indent-guide {background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNgYGBgYHB3d/8PAAOIAdULw8qMAAAAAElFTkSuQmCC) right repeat-y}";var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)}); (function() { 2 | ace.require(["ace/theme/tomorrow_night"], function(m) { 3 | if (typeof module == "object" && typeof exports == "object" && module) { 4 | module.exports = m; 5 | } 6 | }); 7 | })(); 8 | -------------------------------------------------------------------------------- /docs/theme/first-edition.css: -------------------------------------------------------------------------------- 1 | .warning { 2 | display: flex; 3 | justify-content: space-between; 4 | align-items: center; 5 | background-color: rgb(242, 222, 222); 6 | border-bottom-color: rgb(238, 211, 215); 7 | border-bottom-left-radius: 4px; 8 | border-bottom-right-radius: 4px; 9 | border-bottom-style: solid; 10 | border-bottom-width: 0.666667px; 11 | border-image-outset: 0 0 0 0; 12 | border-image-repeat: stretch stretch; 13 | border-image-slice: 100% 100% 100% 100%; 14 | border-image-source: none; 15 | border-image-width: 1 1 1 1; 16 | border-left-color: rgb(238, 211, 215); 17 | border-left-style: solid; 18 | border-left-width: 0.666667px; 19 | border-right-color: rgb(238, 211, 215); 20 | border-right-style: solid; 21 | border-right-width: 0.666667px; 22 | border-top-color: rgb(238, 211, 215); 23 | border-top-left-radius: 4px; 24 | border-top-right-radius: 4px; 25 | border-top-style: solid; 26 | border-top-width: 0.666667px; 27 | color: rgb(185, 74, 72); 28 | margin-bottom: 0px; 29 | margin-left: 0px; 30 | margin-right: 0px; 31 | margin-top: 30px; 32 | padding-bottom: 8px; 33 | padding-left: 14px; 34 | padding-right: 35px; 35 | padding-right: 14px; 36 | padding-top: 8px; 37 | } 38 | .warning strong { 39 | color: rgb(185, 74, 72) 40 | } 41 | .warning a { 42 | color: rgb(0, 136, 204) 43 | } 44 | .warning .message { 45 | margin-right: 14px; 46 | } 47 | .warning .message:last-child { 48 | margin-right: 21px; 49 | } 50 | .warning .button { 51 | border: none; 52 | background: none; 53 | color: inherit; 54 | cursor: pointer; 55 | font-size: 14px; 56 | } 57 | -------------------------------------------------------------------------------- /docs/tomorrow-night.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Night Theme */ 2 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 3 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 4 | /* http://jmblog.github.com/color-themes-for-google-code-highlightjs */ 5 | 6 | /* Tomorrow Comment */ 7 | .hljs-comment { 8 | color: #969896; 9 | } 10 | 11 | /* Tomorrow Red */ 12 | .hljs-variable, 13 | .hljs-attribute, 14 | .hljs-tag, 15 | .hljs-regexp, 16 | .ruby .hljs-constant, 17 | .xml .hljs-tag .hljs-title, 18 | .xml .hljs-pi, 19 | .xml .hljs-doctype, 20 | .html .hljs-doctype, 21 | .css .hljs-id, 22 | .css .hljs-class, 23 | .css .hljs-pseudo { 24 | color: #cc6666; 25 | } 26 | 27 | /* Tomorrow Orange */ 28 | .hljs-number, 29 | .hljs-preprocessor, 30 | .hljs-pragma, 31 | .hljs-built_in, 32 | .hljs-literal, 33 | .hljs-params, 34 | .hljs-constant { 35 | color: #de935f; 36 | } 37 | 38 | /* Tomorrow Yellow */ 39 | .ruby .hljs-class .hljs-title, 40 | .css .hljs-rule .hljs-attribute { 41 | color: #f0c674; 42 | } 43 | 44 | /* Tomorrow Green */ 45 | .hljs-string, 46 | .hljs-value, 47 | .hljs-inheritance, 48 | .hljs-header, 49 | .hljs-name, 50 | .ruby .hljs-symbol, 51 | .xml .hljs-cdata { 52 | color: #b5bd68; 53 | } 54 | 55 | /* Tomorrow Aqua */ 56 | .hljs-title, 57 | .css .hljs-hexcolor { 58 | color: #8abeb7; 59 | } 60 | 61 | /* Tomorrow Blue */ 62 | .hljs-function, 63 | .python .hljs-decorator, 64 | .python .hljs-title, 65 | .ruby .hljs-function .hljs-title, 66 | .ruby .hljs-title .hljs-keyword, 67 | .perl .hljs-sub, 68 | .javascript .hljs-title, 69 | .coffeescript .hljs-title { 70 | color: #81a2be; 71 | } 72 | 73 | /* Tomorrow Purple */ 74 | .hljs-keyword, 75 | .javascript .hljs-function { 76 | color: #b294bb; 77 | } 78 | 79 | .hljs { 80 | display: block; 81 | overflow-x: auto; 82 | background: #1d1f21; 83 | color: #c5c8c6; 84 | padding: 0.5em; 85 | -webkit-text-size-adjust: none; 86 | } 87 | 88 | .coffeescript .javascript, 89 | .javascript .xml, 90 | .tex .hljs-formula, 91 | .xml .javascript, 92 | .xml .vbscript, 93 | .xml .css, 94 | .xml .hljs-cdata { 95 | opacity: 0.5; 96 | } 97 | 98 | .hljs-addition { 99 | color: #718c00; 100 | } 101 | 102 | .hljs-deletion { 103 | color: #c82829; 104 | } 105 | -------------------------------------------------------------------------------- /docs/type-aliases.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Псевдонимы типов - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Псевдонимы типов

61 |

Ключевое слово type позволяет объявить псевдоним другого типа:

62 |

 63 | #![allow(unused)]
 64 | fn main() {
 65 | type Name = String;
 66 | }
 67 | 
68 |

Затем вы можете использовать этот псевдоним вместо реального типа:

69 |

 70 | #![allow(unused)]
 71 | fn main() {
 72 | type Name = String;
 73 | 
 74 | let x: Name = "Hello".to_string();
 75 | }
 76 | 
77 |

Однако, обратите внимание на то что псевдоним не объявляет новый тип. Rust 78 | строго типизированный язык, например у вас не получится сравнить значения двух 79 | различных типов:

80 |
let x: i32 = 5;
 81 | let y: i64 = 5;
 82 | 
 83 | if x == y {
 84 |    // ...
 85 | }
 86 | 
87 |

Вы получите ошибку при компиляции:

88 |
error: mismatched types:
 89 |  expected `i32`,
 90 |     found `i64`
 91 | (expected i32,
 92 |     found i64) [E0308]
 93 |      if x == y {
 94 |              ^
 95 | 
96 |

Но если мы используем псевдоним:

97 |

 98 | #![allow(unused)]
 99 | fn main() {
100 | type Num = i32;
101 | 
102 | let x: i32 = 5;
103 | let y: Num = 5;
104 | 
105 | if x == y {
106 |    // ...
107 | }
108 | }
109 | 
110 |

То этот пример скомпилируется без ошибок. Значения типа Num всегда будут такие 111 | же как и у типа i32.

112 |

Вы также можете использовать псевдонимы типов с обобщённым кодом:

113 |

114 | #![allow(unused)]
115 | fn main() {
116 | use std::result;
117 | 
118 | enum ConcreteError {
119 |     Foo,
120 |     Bar,
121 | }
122 | 
123 | type Result<T> = result::Result<T, ConcreteError>;
124 | }
125 | 
126 |

В этом примере мы создаем свою версию типа Result, который всегда будет 127 | использовать перечисление ConcreteError в Result<T, E> вместо типа E. 128 | Псевдонимы типов часто используются в модулях стандартной библиотеки для 129 | создания своих псевдонимов для Result<T, E>. Например, io::Result.

130 | 131 |
132 |
133 |
134 |
135 | 136 | 137 | -------------------------------------------------------------------------------- /docs/unsized-types.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Безразмерные типы - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Безразмерные типы

61 |

Большинство типов имеют определённый размер в байтах. Этот размер обычно 62 | известен во время компиляции. Например, i32 — это 32 бита, или 4 байта. 63 | Однако, существуют некоторые полезные типы, которые не имеют определённого 64 | размера. Они называются «безразмерными» или «типами динамического размера». Один 65 | из примеров таких типов — это [T]. Этот тип представляет собой 66 | последовательность из определённого числа элементов T. Но мы не знаем, как 67 | много этих элементов, поэтому размер неизвестен.

68 |

Rust понимает несколько таких типов, но их использование несколько ограничено. 69 | Есть три ограничения:

70 |
    71 |
  1. Мы можем работать с экземпляром безразмерного типа только с помощью 72 | указателя. &[T] будет работать, а [T] — нет.
  2. 73 |
  3. Переменные и аргументы не могут иметь тип динамического размера.
  4. 74 |
  5. Только последнее поле структуры может быть безразмерного типа; другие — нет. 75 | Варианты перечислений не могут содержать типы динамического размера в 76 | качестве данных.
  6. 77 |
78 |

А зачем это всё? Поскольку мы можем использовать [T] только через указатель, 79 | если бы язык не поддерживал безразмерные типы, мы бы не смогли написать такой 80 | код:

81 |
impl Foo for str {
 82 | 
83 |

или

84 |
impl<T> Foo for [T] {
 85 | 
86 |

Вместо этого, вам бы пришлось написать:

87 |
impl Foo for &str {
 88 | 
89 |

Таким образом, данная реализация работала бы только для ссылок, и не 90 | поддерживала бы другие типы указателей. А реализацию для безразмерного типа 91 | смогут использовать любые указатели, включая определённые пользователем умные 92 | указатели (позже, когда будут исправлены некоторые ошибки).

93 |

?Sized

94 |

Если вы пишете функцию, принимающую тип динамического размера, вы можете 95 | использовать специальное ограничение ?Sized:

96 |

 97 | #![allow(unused)]
 98 | fn main() {
 99 | struct Foo<T: ?Sized> {
100 |     f: T,
101 | }
102 | }
103 | 
104 |

Этот ? читается как «Т может быть размерным (Sized)». Он означает, что это 105 | ограничение особенное: оно разрешает использование некоторых типов, которые не 106 | могли бы быть использованы в его отсутствие. Таким образом, оно расширяет 107 | множество подходящих типов, а не сужает его. Это можно представить себе как если 108 | бы все типы T неявно были размерными (T: Sized), а ? отменял это 109 | ограничение по умолчанию.

110 | 111 |
112 |
113 |
114 |
115 | 116 | 117 | -------------------------------------------------------------------------------- /docs/using-rust-without-the-standard-library.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Using Rust without the standard library - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Using Rust Without the Standard Library

61 |

Rust’s standard library provides a lot of useful functionality, but assumes 62 | support for various features of its host system: threads, networking, heap 63 | allocation, and others. There are systems that do not have these features, 64 | however, and Rust can work with those too! To do so, we tell Rust that we 65 | don’t want to use the standard library via an attribute: #![no_std].

66 |
67 |

Note: This feature is technically stable, but there are some caveats. For 68 | one, you can build a #![no_std] library on stable, but not a binary. 69 | For details on binaries without the standard library, see the nightly 70 | chapter on #![no_std]

71 |
72 |

To use #![no_std], add a it to your crate root:

73 |

 74 | #![allow(unused)]
 75 | #![no_std]
 76 | 
 77 | fn main() {
 78 | fn plus_one(x: i32) -> i32 {
 79 |     x + 1
 80 | }
 81 | }
 82 | 
83 |

Much of the functionality that’s exposed in the standard library is also 84 | available via the core crate. When we’re using the standard 85 | library, Rust automatically brings std into scope, allowing you to use 86 | its features without an explicit import. By the same token, when using 87 | !#[no_std], Rust will bring core into scope for you, as well as its 88 | prelude. This means that a lot of code will Just Work:

89 |

 90 | #![allow(unused)]
 91 | #![no_std]
 92 | 
 93 | fn main() {
 94 | fn may_fail(failure: bool) -> Result<(), &'static str> {
 95 |     if failure {
 96 |         Err("this didn’t work!")
 97 |     } else {
 98 |         Ok(())
 99 |     }
100 | }
101 | }
102 | 
103 | 104 |
105 |
106 |
107 |
108 | 109 | 110 | -------------------------------------------------------------------------------- /docs/vectors.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: Вектора - Язык программирования Rust 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 |
30 |
31 | Вы читаете устаревшую версию TRPL. Новая версия здесь. 32 | 35 |
36 | 37 | 57 | 58 |
59 |
60 |

% Вектора

61 |

«Вектор» — это динамический или, по-другому, «растущий» массив, реализованный в 62 | виде стандартного библиотечного типа Vec<T> (где <T> является 63 | обобщённым типом). Вектора всегда размещают данные в куче. Вы можете 64 | создавать их с помощью макроса vec!:

65 |

 66 | #![allow(unused)]
 67 | fn main() {
 68 | let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>
 69 | }
 70 | 
71 |

(Заметьте, что, в отличие от макроса println!, который мы использовали ранее, 72 | с vec! используются квадратные скобки []. Rust разрешает использование и 73 | круглых, и квадратных скобок в обеих ситуациях — это просто стилистическое 74 | соглашение.)

75 |

Для создания вектора из повторяющихся значений есть другая форма vec!:

76 |

 77 | #![allow(unused)]
 78 | fn main() {
 79 | let v = vec![0; 10]; // десять нулей
 80 | }
 81 | 
82 |

Доступ к элементам

83 |

Чтобы получить значение по определенному индексу в векторе, мы используем []:

84 |

 85 | #![allow(unused)]
 86 | fn main() {
 87 | let v = vec![1, 2, 3, 4, 5];
 88 | 
 89 | println!("Третий элемент вектора v равен {}", v[2]);
 90 | }
 91 | 
92 |

Индексы отсчитываются от 0, так что третьим элементом является v[2].

93 |

Обход

94 |

Вы можете обойти элементы вектора с помощью for. Есть три варианта:

95 |

 96 | #![allow(unused)]
 97 | fn main() {
 98 | let mut v = vec![1, 2, 3, 4, 5];
 99 | 
100 | for i in &v {
101 |     println!("Ссылка {}", i);
102 | }
103 | 
104 | for i in &mut v {
105 |     println!("Изменяемая ссылка {}", i);
106 | }
107 | 
108 | for i in v {
109 |     println!("Владение вектором и его элементами {}", i);
110 | }
111 | }
112 | 
113 |

У векторов есть много других полезных методов, о которых вы можете прочитать в 114 | документации API.

115 | 116 |
117 |
118 |
119 |
120 | 121 | 122 | -------------------------------------------------------------------------------- /script/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | REV=$(git rev-parse --short HEAD) 4 | 5 | sed "s//$REV/g" README.rev.template.md >> README.md 6 | 7 | rustbook build 8 | 9 | sed -i "s/@import url('..\/rust.css');/@import url('.\/rust.css');/g" _book/rustbook.css 10 | sed -i "s/ 28 | -------------------------------------------------------------------------------- /theme/index.hbs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Outdated link: {{ title }} 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | {{#each additional_css}} 24 | 25 | {{/each}} 26 | 27 | 28 |
29 |
30 | {{> header}} 31 |
32 |
33 | {{{ content }}} 34 |
35 |
36 |
37 |
38 | 39 | 40 | --------------------------------------------------------------------------------