@@ -75,79 +75,77 @@ immutable variable`), бо ми намагалися присвоїти друг
75
75
``` rust
76
76
fn main () {
77
77
let mut x = 5 ;
78
- println! (" The value of x is : {}" , x );
78
+ println! (" Значення x : {}" , x );
79
79
x = 6 ;
80
- println! (" The value of x is : {}" , x );
80
+ println! (" Значення x : {}" , x );
81
81
}
82
82
```
83
83
84
- Запустивши програму, ми отримаємо:
84
+ Запустивши програму ми отримаємо:
85
85
86
86
``` text
87
87
$ cargo run
88
88
Compiling variables v0.1.0 (file:///projects/variables)
89
89
Running `target/debug/variables`
90
- The value of x is : 5
91
- The value of x is : 6
90
+ Значення x : 5
91
+ Значення x : 6
92
92
```
93
93
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
+ верхнього регістру із підкресленнями між словам:
125
124
126
125
```
127
126
const MAX_POINTS: u32 = 100_000;
128
127
```
129
128
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
+ кількість секунд у році .
135
134
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
+ яке буде необхідно змінити, у разі потреби оновити жорстко задане значення .
140
139
141
- ### Shadowing
140
+ ### Затінення
142
141
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 ` та імені цієї змінної:
149
147
150
- <span class =" filename " >Filename : src/main.rs</span >
148
+ <span class =" filename " >Файл : src/main.rs</span >
151
149
152
150
``` rust
153
151
fn main () {
@@ -157,53 +155,52 @@ fn main() {
157
155
158
156
let x = x * 2 ;
159
157
160
- println! (" The value of x is : {}" , x );
158
+ println! (" Значення x : {}" , x );
161
159
}
162
160
```
163
161
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
+ цю програму, вона виведе :
169
167
170
168
``` text
171
169
$ cargo run
172
170
Compiling variables v0.1.0 (file:///projects/variables)
173
171
Running `target/debug/variables`
174
- The value of x is : 12
172
+ Значення x : 12
175
173
```
176
174
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
+ значення, але змінна буде сталою після виконання цих перетворень .
181
179
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
+ символи пробілу, але насправді ми хочемо зберігати це значення як число :
187
185
188
186
``` rust
189
187
let spaces = " " ;
190
188
let spaces = spaces . len ();
191
189
```
192
190
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 ` , як показано :
199
197
200
198
``` rust,ignore
201
199
let mut spaces = " ";
202
200
spaces = spaces.len();
203
201
```
204
202
205
- we’ll get a compile-time error because we’re not allowed to mutate a variable’s
206
- type:
203
+ ми отримаємо помилку часу компіляції, бо не можна змінювати тип змінної:
207
204
208
205
``` text
209
206
error[E0308]: mismatched types
@@ -216,5 +213,5 @@ error[E0308]: mismatched types
216
213
= note: found type `usize`
217
214
```
218
215
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