Skip to content

Commit 35344b2

Browse files
committed
3-1 completed
1 parent f8efbcd commit 35344b2

File tree

4 files changed

+112
-97
lines changed

4 files changed

+112
-97
lines changed

CONTRIBUTING.md

+2-18
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,6 @@
11
# Участь у проекті перекладу
22

3-
Тут будуть викладатися поточні потреби проекту.
3+
Перекладаємо другу редакцію.
44

5-
Поки що - короткий словник специфічних термінів:
5+
Тут будуть викладатися поточні потреби проекту.
66

7-
directory - тека
8-
> може, замінити на "директорію"?
9-
macro - макрос
10-
> "макровизначення" - надто довго
11-
listring - роздрук
12-
string - стрічка
13-
> наприклад, змінна
14-
line - рядок
15-
> наприклад, у файлі
16-
immutable - сталий
17-
mutable - несталий
18-
> відкинуті варіанти "змінний" (фу), "змінюваний", "такий, що може змінюватися",
19-
> "мінливий"
20-
bind (bound) - зв'язувати, зв'язаний
21-
enum - енум
22-
> специфічний термін, не бачу сенсу заміняти його на "перел" (від "перелік")

DICTIONARY.md

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
Поки що - короткий словник специфічних термінів:
2+
3+
bind - зв'язувати
4+
directory - тека
5+
> може, замінити на "директорію"?
6+
enum - енум
7+
> специфічний термін, не бачу сенсу заміняти його на "перел" (від "перелік")
8+
> абощо
9+
hardcoded - жорстко заданий
10+
immutable - сталий
11+
> пор. mutable
12+
line - рядок
13+
> наприклад, у файлі; пор. string
14+
listring - роздрук
15+
macro - макрос
16+
> "макровизначення" - надто довго
17+
mutable - несталий
18+
> відкинуті варіанти "змінний" (фу), "змінюваний", "такий, що може змінюватися",
19+
> "мінливий"
20+
Rustacean - растацеанець
21+
scope - область видимості
22+
> жахливий русизм, залюбки поміняю на щось інше
23+
shadowing - затінення
24+
statement - оператор
25+
>так, дуже погано
26+
string - стрічка
27+
> наприклад, змінна; пор. line

README.md

+7
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,13 @@ $ mdbook test
5959
[contrib]: https://github.com/rust-lang/book/blob/master/CONTRIBUTING.md
6060
[contrib-uk]: https://github.com/pavloslav/rust-book-ukrainian/blob/master/CONTRIBUTING.md
6161

62+
### Словник
63+
64+
Для перекладу формується невеликий [словничок][dictionary], пропозиції і
65+
зауваження заохочуються.
66+
67+
[dictionary] https://github.com/pavloslav/rust-book-ukrainian/blob/master/DICTIONARY.md
68+
6269
### Інші переклади
6370

6471
Особливо важлива ваша допомога в перекладанні! Прогляньте повідомлення,

second-edition/src/ch03-01-variables-and-mutability.md

+76-79
Original file line numberDiff line numberDiff line change
@@ -75,79 +75,77 @@ immutable variable`), бо ми намагалися присвоїти друг
7575
```rust
7676
fn main() {
7777
let mut x = 5;
78-
println!("The value of x is: {}", x);
78+
println!("Значення x: {}", x);
7979
x = 6;
80-
println!("The value of x is: {}", x);
80+
println!("Значення x: {}", x);
8181
}
8282
```
8383

84-
Запустивши програму, ми отримаємо:
84+
Запустивши програму ми отримаємо:
8585

8686
```text
8787
$ cargo run
8888
Compiling variables v0.1.0 (file:///projects/variables)
8989
Running `target/debug/variables`
90-
The value of x is: 5
91-
The value of x is: 6
90+
Значення x: 5
91+
Значення x: 6
9292
```
9393

94-
Using `mut`, we’re allowed to change the value that `x` binds to from `5` to
95-
`6`. In some cases, you’ll want to make a variable mutable because it makes the
96-
code more convenient to write than an implementation that only uses immutable
97-
variables.
98-
99-
There are multiple trade-offs to consider, in addition to the prevention of
100-
bugs. For example, in cases where you’re using large data structures, mutating
101-
an instance in place may be faster than copying and returning newly allocated
102-
instances. With smaller data structures, always creating new instances and
103-
writing in a more functional programming style may be easier to reason about,
104-
so the lower performance penalty might be worth it to gain that clarity.
105-
106-
### Differences Between Variables and Constants
107-
108-
Not being able to change the value of a variable might have reminded you of
109-
another programming concept that most languages have: *constants*. Constants
110-
are also values bound to a name that are not allowed to change, but there are a
111-
few differences between constants and variables. First, using `mut` with
112-
constants is not allowed: constants aren't only immutable by default, they're
113-
always immutable. Constants are declared using the `const` keyword instead of
114-
the `let` keyword, and the type of the value *must* be annotated. We're about
115-
to cover types and type annotations in the next section, “Data Types,” so don't
116-
worry about the details right now. Constants can be declared in any scope,
117-
including the global scope, which makes them useful for a value that many parts
118-
of your code need to know about. The last difference is that constants may only
119-
be set to a constant expression, not the result of a function call or any other
120-
value that could only be used at runtime.
121-
122-
Here's an example of a constant declaration where the constant's name is
123-
`MAX_POINTS` and its value is set to 100,000. Rust constant naming convention
124-
is to use all upper case with underscores between words:
94+
Застосувавши `mut`, ми дозволили змінити значення, прив'язане до `x`, з `5` на
95+
`6`. У деяких випадках, вам захочеться робити зміннні несталими, бо так зручніше
96+
писати код, ніж в реалізації з виключно сталими змінними.
97+
98+
Варто розглядати й інші аспекти, крім запобігання вадам. Наприклад, якщо ви
99+
використовуєте великі структури даних, змінювати екземпляр на місці може бути
100+
швидше, ніж копіювати і повертати наново виділений екземпляр. Для менших
101+
структур даних може бути зручнішим розмірковувати про код, написаний у більш
102+
функціональному стилі, з постійним створенням нових екземплярів, тому може бути
103+
варто знизити продуктивність заради збільшення ясності.
104+
105+
### Різниця між змінними та константами
106+
107+
Неможливість змінити значення змінної може нагадати вам про іншу концепцію
108+
программування, що є в більшості мов: *константи*. Константи - це так само
109+
значення, прив'язані до імені, які не можна змінювати, але є кілька різниць між
110+
константами і змінними. По-перше, використання `mut` з константами неможливе:
111+
константи не тільки типово незмінні, вони завжди незмінні. Константи
112+
проголошуються ключовим словом `const` замість `let`, і тип значення *має* явно
113+
позначатися. Ми розкажемо про типи і їхнє позначення в наступному розділі, "Типи
114+
даних", тому не хвилюйтеся зараз про деталі. Константи можуть проголошуватися
115+
в будь-якій області видимості, у тому числі глобальній, що робить їх корисними
116+
для зберігання значення, яке використовується у багатьох частинах вашого коду.
117+
Остання відмнінність полягає в тому, що константи можуть набувати тільки
118+
значення константних виразів, не результатів виклику функції чи інших значень,
119+
які можуть бути використані лише під час виконання програми.
120+
121+
Ось приклад проголошення константи, де константа зветься `MAX_POINTS`, а її
122+
значення є 100,000. Угода про назви констант в Rust вимагає використання
123+
верхнього регістру із підкресленнями між словам:
125124

126125
```
127126
const MAX_POINTS: u32 = 100_000;
128127
```
129128

130-
Constants are valid for the entire lifetime of a program, within the scope they
131-
were declared in. That makes constants useful for values in your application
132-
domain that multiple part of the program might need to know about, such as the
133-
maximum number of points any player of a game is allowed to earn or the number
134-
of seconds in a year.
129+
Константи діють протягом усього часу життя програми, всередині тієї області
130+
видимості, де вони були проголошені. Це робить константи корисними для
131+
зберігання значень у вашому додатку, про які необхідно знати багатьом частинам
132+
програми, наприклад максимальна кількість балів, яку може отримати гравець чи
133+
кількість секунд у році.
135134

136-
Documenting hardcoded values used throughout your program by naming them as
137-
constants is useful to convey the meaning of that value to future maintainers
138-
of the code. It also helps to have only one place in your code that you would
139-
need to change if the hardcoded value needed to be updated in the future.
135+
Корисно документувати жорстко задані значення, що використовуються по всій
136+
програмі, позначаючи їх константами, щоб передати сенс цього значення тим, хто
137+
супроводжуватиме код. Це також корисно тим, що ви в коді буде тільки одне місце,
138+
яке буде необхідно змінити, у разі потреби оновити жорстко задане значення.
140139

141-
### Shadowing
140+
### Затінення
142141

143-
As we saw in the guessing game tutorial in Chapter 2, we can declare new
144-
variables with the same name as a previous variables, and the new variable
145-
*shadows* the previous variable. Rustaceans say that the first variable is
146-
*shadowed* by the second, which means that the second variable’s value is what
147-
we’ll see when we use the variable. We can shadow a variable by using the same
148-
variable’s name and repeating the use of the `let` keyword as follows:
142+
Як ми бачили у Розділі 2, можна проголошувати нові змінні із таким самим іменем,
143+
як і в минулих змінних, і нова змінна *затінює* (*shadows*) попередню змінну.
144+
Растацеанці кажуть, що перша змінна *затінена* (*shadowed*) другою, що означає,
145+
що при використанні змінної ми отримаємо значення другої змінної. Ми можемо
146+
затінити змінну за допомогою ключового слова `let` та імені цієї змінної:
149147

150-
<span class="filename">Filename: src/main.rs</span>
148+
<span class="filename">Файл: src/main.rs</span>
151149

152150
```rust
153151
fn main() {
@@ -157,53 +155,52 @@ fn main() {
157155

158156
let x = x * 2;
159157

160-
println!("The value of x is: {}", x);
158+
println!("Значення x: {}", x);
161159
}
162160
```
163161

164-
This program first binds `x` to a value of `5`. Then it shadows `x` by
165-
repeating `let x =`, taking the original value and adding `1` so the value of
166-
`x` is then `6`. The third `let` statement also shadows `x`, taking the
167-
previous value and multiplying it by `2` to give `x` a final value of `12`.
168-
When you run this program, it will output the following:
162+
Ця програма спершу прив'язує `x` до значення `5`. Потім затінює `x` повторенням
163+
`let x =`, взявши початкове значення і додавши до нього `1`, так що значення `x`
164+
стає `6`. Третій оператор `let` також затінює `x`, бере попереднє значення і
165+
множить його на `1`, щоб надати `x` остатночного значення `12`. Якщо запустити
166+
цю програму, вона виведе:
169167

170168
```text
171169
$ cargo run
172170
Compiling variables v0.1.0 (file:///projects/variables)
173171
Running `target/debug/variables`
174-
The value of x is: 12
172+
Значення x: 12
175173
```
176174

177-
This is different than marking a variable as `mut`, because unless we use the
178-
`let` keyword again, we’ll get a compile-time error if we accidentally try to
179-
reassign to this variable. We can perform a few transformations on a value but
180-
have the variable be immutable after those transformations have been completed.
175+
Це відрізняється від позначення змінної `mut`, адже якщо ми знову не
176+
використаємо ключове слово `let`, отримаємо помилку часу компіляції, якщо
177+
випадково спробуємо переприсвоїти значення цієї змінної. Ми можемо перетворювати
178+
значення, але змінна буде сталою після виконання цих перетворень.
181179

182-
The other difference between `mut` and shadowing is that because we’re
183-
effectively creating a new variable when we use the `let` keyword again, we can
184-
change the type of the value, but reuse the same name. For example, say our
185-
program asks a user to show how many spaces they want between some text by
186-
inputting space characters, but we really want to store that input as a number:
180+
Інша різниця між `mut` та затіненням полягає в тому, що оскільки коли пишемо
181+
знову ключове слово `let`, насправді ми створюємо нову змінну, тоже можемо
182+
змінити тип значення, але залишити ім'я. Наприклад, хай наша програма просить
183+
користувача вказати, скільки пробілів має бути всередині якогось тексту, ввівши
184+
символи пробілу, але насправді ми хочемо зберігати це значення як число:
187185

188186
```rust
189187
let spaces = " ";
190188
let spaces = spaces.len();
191189
```
192190

193-
This construct is allowed because the first `spaces` variable is a string type,
194-
and the second `spaces` variable, which is a brand-new variable that happens to
195-
have the same name as the first one, is a number type. Shadowing thus spares us
196-
from having to come up with different names, like `spaces_str` and
197-
`spaces_num`; instead, we can reuse the simpler `spaces` name. However, if we
198-
try to use `mut` for this, as shown here:
191+
Ця конструкція можлива, бо перша змінна `spaces` має стрічковий тип, а друга
192+
змінна `spaces`, що є повністю новою змінною, якій трапилося мати таке саме
193+
ім'я, має числовий тип. Затінення, таким чином, позбавляє нас необхідності
194+
придумувати різні імена, на кшталт `spaces_str` та `spaces_num`; натомість, ми
195+
можемо заново використати простіше ім'я `spaces`. Але якщо ми спробуємо
196+
скористатися `mut`, як показано:
199197

200198
```rust,ignore
201199
let mut spaces = " ";
202200
spaces = spaces.len();
203201
```
204202

205-
we’ll get a compile-time error because we’re not allowed to mutate a variable’s
206-
type:
203+
ми отримаємо помилку часу компіляції, бо не можна змінювати тип змінної:
207204

208205
```text
209206
error[E0308]: mismatched types
@@ -216,5 +213,5 @@ error[E0308]: mismatched types
216213
= note: found type `usize`
217214
```
218215

219-
Now that we’ve explored how variables work, let’s look at more data types they
220-
can have.
216+
Тепер, дослідивши, як працюють змінні, погляньмо, які типи данних вони можуть
217+
зберігати.

0 commit comments

Comments
 (0)