1
- ## Defining and Instantiating Structs
1
+ ## 구조체 정의 및 인스턴트화
2
2
3
- Structs are similar to tuples, which were discussed in Chapter 3. Like tuples,
4
- the pieces of a struct can be different types. Unlike with tuples, you’ll name
5
- each piece of data so it’s clear what the values mean. As a result of these
6
- names, structs are more flexible than tuples: you don’t have to rely on the
7
- order of the data to specify or access the values of an instance .
3
+ 구조체는 3장에서 배운 튜플과 비슷합니다.
4
+ 튜플처럼 구조체의 구성 요소들은 각각 다른 타입이 될 수 있습니다.
5
+ 그리고 여기에 더해서, 구조체는 각각의 구성 요소에 이름을 붙일 수 있습니다.
6
+ 따라서 각 요소가 더 명확한 의미를 갖게 되고, 특정 요소에 접근할 때
7
+ 순서에 의존할 필요도 사라집니다. 결론적으로, 튜플보다 유연하게 사용할 수 있습니다 .
8
8
9
- To define a struct, we enter the keyword ` struct ` and name the entire struct. A
10
- struct’s name should describe the significance of the pieces of data being
11
- grouped together. Then, inside curly brackets, we define the names and types of
12
- the pieces of data, which we call * fields * . For example, Listing 5-1 shows a
13
- struct that stores information about a user account .
9
+ 구조체를 정의할 땐 ` struct ` 키워드와 해당 구조체에 지어줄 이름을 입력하면 됩니다.
10
+ 이때 구조체 이름은 함께 묶을 데이터의 의미에 맞도록 지어주세요.
11
+ 이후 중괄호 안에서는 필드( * field * )라 하는
12
+ 각 구성 요소의 이름 및 타입을 정의합니다.
13
+ 다음 Listing 5-1은 사용자 계정 정보를 저장하는 구조체입니다 .
14
14
15
15
``` rust
16
16
struct User {
@@ -21,17 +21,17 @@ struct User {
21
21
}
22
22
```
23
23
24
- <span class =" caption " >Listing 5-1: A ` User ` struct definition </span >
24
+ <span class =" caption " >Listing 5-1: 사용자 계정 정보를 저장하는 ` User ` 구조체 정의 </span >
25
25
26
- To use a struct after we’ve defined it, we create an * instance * of that struct
27
- by specifying concrete values for each of the fields. We create an instance by
28
- stating the name of the struct and then add curly brackets containing `key:
29
- value` pairs, where the keys are the names of the fields and the values are the
30
- data we want to store in those fields. We don’t have to specify the fields in
31
- the same order in which we declared them in the struct. In other words, the
32
- struct definition is like a general template for the type, and instances fill
33
- in that template with particular data to create values of the type. For
34
- example, we can declare a particular user as shown in Listing 5-2 .
26
+ 정의한 구조체를 사용하려면 해당 구조체 내
27
+ 각 필드의 값을 정해 인스턴스( * instance * )를 생성해야 합니다.
28
+ 인스턴스를 생성하려면 먼저 구조체의 이름을 적고, 중괄호를 열고,
29
+ 그 안에 필드의 이름(key)와 해당 필드에 저장할 값을 ` key:value ` 형태로 추가 해야합니다.
30
+ 이때 필드의 순서는 구조체를 정의했을 때와 동일하지 않아도 됩니다.
31
+ 요약하자면, 구조체 정의는 대충 해당 구조체에 무엇이 들어갈지를 정해둔 양식이며,
32
+ 인스턴스는 거기에 실제 값을 넣은 것이라고 생각하시면 됩니다.
33
+ 예시로 확인해 보죠. Listing 5-2 에서 앞서 정의한 ` User ` 구조체로
34
+ 사용자를 선언해보겠습니다 .
35
35
36
36
``` rust
37
37
# struct User {
@@ -49,14 +49,14 @@ let user1 = User {
49
49
};
50
50
```
51
51
52
- <span class =" caption " >Listing 5-2: Creating an instance of the ` User `
53
- struct </span >
52
+ <span class =" caption " >Listing 5-2: ` User ` 구조체의
53
+ 인스턴스 생성 </span >
54
54
55
- To get a specific value from a struct, we can use dot notation. If we wanted
56
- just this user’s email address, we could use ` user1.email ` wherever we wanted
57
- to use this value. If the instance is mutable, we can change a value by using
58
- the dot notation and assigning into a particular field. Listing 5-3 shows how
59
- to change the value in the ` email ` field of a mutable ` User ` instance .
55
+ 구조체 내 특정 값은 점(.) 표기법으로 얻어올 수 있습니다.
56
+ 사용자의 이메일 주소를 얻어야 한다치면 ` user1.email ` 처럼 사용할 수 있죠.
57
+ 변경 가능한 인스턴스라면, 같은 방식으로 특정 필드의 값을 변경할 수도 있습니다.
58
+ 다음 Listing 5-3 이 변경 가능한 인스턴스의
59
+ ` email ` 필드 값을 변경하는 예시입니다 .
60
60
61
61
``` rust
62
62
# struct User {
@@ -76,17 +76,17 @@ let mut user1 = User {
76
76
user1 . email
= String :: from (
" [email protected] " );
77
77
```
78
78
79
- <span class =" caption " >Listing 5-3: Changing the value in the ` email ` field of a
80
- ` User ` instance </span >
79
+ <span class =" caption " >Listing 5-3: ` User ` 인스턴스의
80
+ ` email ` 필드 값 변경 </span >
81
81
82
- Note that the entire instance must be mutable; Rust doesn’t allow us to mark
83
- only certain fields as mutable. As with any expression, we can construct a new
84
- instance of the struct as the last expression in the function body to
85
- implicitly return that new instance .
82
+ 가변성은 해당 인스턴스 전체가 지니게 됩니다.
83
+ 일부 필드만 변경 가능하도록 만들 수는 없으니, 기억해두시기 바랍니다.
84
+ 또한, 구조체도 다른 표현식과 마찬가지로 함수 마지막 표현식에서
85
+ 암묵적으로 새 인스턴스를 생성하고 반환할 수 있습니다 .
86
86
87
- Listing 5-4 shows a ` build_user ` function that returns a ` User ` instance with
88
- the given email and username. The ` active ` field gets the value of ` true ` , and
89
- the ` sign_in_count ` gets a value of ` 1 ` .
87
+ Listing 5-4 에선 ` build_user ` 함수가 사용자 이메일과 이름을 전달 받고,
88
+ ` acitve ` , ` sign_in_count ` 를 각각 ` true ` , ` 1 ` 로 설정한
89
+ ` User ` 인스턴스를 반환하는 모습을 보여줍니다 .
90
90
91
91
``` rust
92
92
# struct User {
@@ -106,20 +106,20 @@ fn build_user(email: String, username: String) -> User {
106
106
}
107
107
```
108
108
109
- <span class =" caption " >Listing 5-4: A ` build_user ` function that takes an email
110
- and username and returns a ` User ` instance </span >
109
+ <span class =" caption " >Listing 5-4: 사용자의 이메일과 이름을 전달 받고
110
+ ` User ` 인스턴스를 반환하는 ` build_user ` 함수 </span >
111
111
112
- It makes sense to name the function parameters with the same name as the struct
113
- fields, but having to repeat the ` email ` and ` username ` field names and
114
- variables is a bit tedious. If the struct had more fields, repeating each name
115
- would get even more annoying. Luckily, there’s a convenient shorthand!
112
+ 특별히 나쁜 부분은 없지만, 매개변수명과 구조체 필드명이
113
+ ` email ` , ` username ` 으로 동일한데 굳이 반복해서 작성하는 건 귀찮은 감이 있군요.
114
+ 구조체의 필드 개수가 많아지면 많아질수록 이런 귀찮음은 커질 겁니다.
115
+ 한번 축약법을 사용해볼까요?
116
116
117
- ### Using the Field Init Shorthand when Variables and Fields Have the Same Name
117
+ ## 변수명과 필드명이 같을 때 간단하게 필드 초기화하기
118
118
119
- Because the parameter names and the struct field names are exactly the same in
120
- Listing 5-4, we can use the * field init shorthand* syntax to rewrite
121
- ` build_user ` so that it behaves exactly the same but doesn’t have the
122
- repetition of ` email ` and ` username ` , as shown in Listing 5-5 .
119
+ Listing 5-4 처럼 변수명과 구조체 필드명이 같을 땐,
120
+ 필드 초기화 축약법( * field init shorthand* )을 사용해서 더 적은 타이핑으로
121
+ 같은 기능을 구현할 수 있습니다. 다음 Listing 5-5 는 ` email ` , ` username ` 을
122
+ 반복 작성하는 대신 필드 초기화 축약법을 사용한 예제입니다 .
123
123
124
124
``` rust
125
125
# struct User {
@@ -139,24 +139,24 @@ fn build_user(email: String, username: String) -> User {
139
139
}
140
140
```
141
141
142
- <span class =" caption " >Listing 5-5: A ` build_user ` function that uses field init
143
- shorthand because the ` email ` and ` username ` parameters have the same name as
144
- struct fields </span >
142
+ <span class =" caption " >Listing 5-5: 변수명과 필드명이 같던
143
+ ` email ` , ` username ` 에 필드 초기화 축약법을 적용한
144
+ ` build_user ` 함수 </span >
145
145
146
- Here, we’re creating a new instance of the ` User ` struct, which has a field
147
- named ` email ` . We want to set the ` email ` field’s value to the value in the
148
- ` email ` parameter of the ` build_user ` function. Because the ` email ` field and
149
- the ` email ` parameter have the same name, we only need to write ` email ` rather
150
- than ` email: email ` .
146
+ 이번에는 ` build_user ` 함수에서
147
+ ` User ` 구조체의 인스턴스를 생성할 때
148
+ ` email: email ` 처럼 작성하는 대신,
149
+ 변수명과 필드명이 같다는 점을 이용해 ` email ` 로만 작성한 모습입니다.
150
+ 물론, 함수는 이전과 같이 잘 작동합니다 .
151
151
152
- ### Creating Instances From Other Instances With Struct Update Syntax
152
+ ### 기존 인스턴스를 이용해 새 인스턴스를 만들 때 구조체 갱신법 사용하기
153
153
154
- It’s often useful to create a new instance of a struct that uses most of an old
155
- instance’s values but changes some. You’ll do this using * struct update syntax* .
154
+ 기존에 있던 인스턴스에서 대부분의 값을 유지한 채로 몇몇 값만 바꿔 새로운 인스턴스를 생성하게 되는 경우가 간혹 있습니다.
155
+ 그럴 때 유용한 게 바로 구조체 갱신법( * struct update syntax* )입니다 .
156
156
157
- First, Listing 5-6 shows how we create a new ` User ` instance in ` user2 ` without
158
- the update syntax. We set new values for ` email ` and ` username ` but otherwise
159
- use the same values from ` user1 ` that we created in Listing 5-2 .
157
+ 먼저 구조체 갱신법을 사용하지 않았을 때를 살펴봅시다.
158
+ Listing 5-6 은 Listing 5-2 에서 만든 ` user1 ` 을 구조체 갱신법 없이
159
+ ` email ` 과 ` username ` 만 새로운 값으로 변경해 ` user2 ` 를 생성하는 코드입니다 .
160
160
161
161
``` rust
162
162
# struct User {
@@ -181,12 +181,12 @@ let user2 = User {
181
181
};
182
182
```
183
183
184
- <span class =" caption " >Listing 5-6: Creating a new ` User ` instance using some of
185
- the values from ` user1 ` </span >
184
+ <span class =" caption " >Listing 5-6: ` user1 ` 의 일부 값을 이용해
185
+ 새로운 ` User ` 인스턴스를 생성 </span >
186
186
187
- Using struct update syntax, we can achieve the same effect with less code, as
188
- shown in Listing 5-7. The syntax ` .. ` specifies that the remaining fields not
189
- explicitly set should have the same value as the fields in the given instance .
187
+ 이번엔 구조체 갱신법을 사용해볼까요?
188
+ 다음 Listing 5-7 처럼, 구조체 갱신법은 더 적은 코드로 같은 효과를 낼 수 있습니다.
189
+ ` .. ` 은 따로 명시된 필드를 제외한 나머지 필드를, 주어진 인스턴스의 필드 값으로 설정하는 구문입니다 .
190
190
191
191
``` rust
192
192
# struct User {
@@ -210,26 +210,26 @@ let user2 = User {
210
210
};
211
211
```
212
212
213
- <span class =" caption " >Listing 5-7: Using struct update syntax to set new
214
- ` email ` and ` username ` values for a ` User ` instance but use the rest of the
215
- values from the fields of the instance in the ` user1 ` variable </span >
213
+ <span class =" caption " >Listing 5-7: 새로운 ` email ` , ` username ` 값으로
214
+ ` User ` 구조체의 인스턴스를 생성하되, 나머지 필드는
215
+ 구조체 갱신법을 이용해 ` user1 ` 의 필드 값을 사용하기 </span >
216
216
217
- The code in Listing 5-7 also creates an instance in ` user2 ` that has a
218
- different value for ` email ` and ` username ` but has the same values for the
219
- ` active ` and ` sign_in_count ` fields from ` user1 ` .
217
+ Listing 5-7 은 ` user2 ` 인스턴스를 생성할때
218
+ ` active ` , ` sign_in_count ` 는 ` user1 ` 의 필드와 같은 값을 갖고
219
+ ` email ` , ` username ` 은 다른 값을 갖도록 하는 코드입니다 .
220
220
221
- ### Using Tuple Structs without Named Fields to Create Different Types
221
+ ### 필드명이 없는, 타입 구분용 튜플 구조체
222
222
223
- You can also define structs that look similar to tuples, called * tuple
224
- structs * . Tuple structs have the added meaning the struct name provides but
225
- don’t have names associated with their fields; rather, they just have the types
226
- of the fields. Tuple structs are useful when you want to give the whole tuple a
227
- name and make the tuple be a different type from other tuples, and naming each
228
- field as in a regular struct would be verbose or redundant .
223
+ 구조체를 사용해 튜플과 유사한 형태의 튜플 구조체( * tuple structs * )를
224
+ 정의할 수도 있습니다. 튜플 구조체는 필드의 이름을 붙이지 않고
225
+ 필드 타입 만을 정의하며, 구조체 명으로 의미를 갖는 구조체입니다.
226
+ 이는 튜플 전체에 이름을 지어주거나 특정 튜플을 다른 튜플과 구분 짓고 싶은데,
227
+ 그렇다고 각 필드명을 일일이 정해 일반적인 구조체를 만드는 것은
228
+ 배보다 배꼽이 더 큰 격이 될 수 있을 때 유용합니다 .
229
229
230
- To define a tuple struct, start with the ` struct ` keyword and the struct name
231
- followed by the types in the tuple. For example, here are definitions and
232
- usages of two tuple structs named ` Color ` and ` Point ` :
230
+ 튜플 구조체의 정의는 일반적인 구조체처럼 ` struct ` 키워드와 구조체 명으로 시작되나,
231
+ 그 뒤에는 타입들로 이루어진 튜플이 따라옵니다. 예시로 살펴볼까요?
232
+ 다음은 각각 ` Color ` , ` Point ` 라는 두 개의 튜플 구조체 정의 및 사용 예시입니다.
233
233
234
234
``` rust
235
235
struct Color (i32 , i32 , i32 );
@@ -239,35 +239,35 @@ let black = Color(0, 0, 0);
239
239
let origin = Point (0 , 0 , 0 );
240
240
```
241
241
242
- Note that the ` black ` and ` origin ` values are different types, because they’re
243
- instances of different tuple structs. Each struct you define is its own type,
244
- even though the fields within the struct have the same types. For example, a
245
- function that takes a parameter of type ` Color ` cannot take a ` Point ` as an
246
- argument, even though both types are made up of three ` i32 ` values. Otherwise,
247
- tuple struct instances behave like tuples: you can destructure them into their
248
- individual pieces, you can use a ` . ` followed by the index to access an
249
- individual value, and so on .
242
+ ` black ` , ` origin ` 이 서로 다른 튜플 구조체의 인스턴스이므로,
243
+ 타입이 서로 달라진다는 점이 중요합니다.
244
+ 구조체 내 필드 구성이 같더라도 각각의 구조체는 별도의 타입이기 때문이죠.
245
+ 즉, ` Color ` 타입과 ` Point ` 타입은 둘 다 ` i32 ` 값 3 개로 이루어진 타입이지만,
246
+ ` Color ` 타입을 매개변수로 받는 함수에
247
+ ` Point ` 타입을 인자로 넘겨주는 건 불가능합니다.
248
+ 앞서 말한 점을 제외하면 튜플처럼 사용할 수 있습니다.
249
+ 여러 부분으로 해체할 수도 있고, ` . ` 과 색인으로 요소에 접근할 수도 있죠 .
250
250
251
- ### Unit-Like Structs Without Any Fields
251
+ ### 필드가 없는 유사 유닛 구조체
252
252
253
- You can also define structs that don’t have any fields! These are called
254
- * unit-like structs * because they behave similarly to ` () ` , the unit type.
255
- Unit -like structs can be useful in situations in which you need to implement a
256
- trait on some type but don’t have any data that you want to store in the type
257
- itself. We’ll discuss traits in Chapter 10 .
253
+ 필드가 아예 없는 구조체를 정의할 수도 있습니다.
254
+ 이는 유닛 타입인 ` () ` 과 비슷하게 동작하므로
255
+ 유사 유닛 구조체( * unit -like structs* ) 라 지칭하며,
256
+ 어떤 타입을 내부 데이터 저장 없이 10장에서 배울 트레잇을
257
+ 구현하기만 하는 용도로 사용할 때 주로 활용됩니다 .
258
258
259
- > ### Ownership of Struct Data
259
+ > ### 구조체 데이터의 소유권
260
260
>
261
- > In the ` User ` struct definition in Listing 5-1, we used the owned ` String `
262
- > type rather than the ` &str ` string slice type. This is a deliberate choice
263
- > because we want instances of this struct to own all of its data and for that
264
- > data to be valid for as long as the entire struct is valid .
261
+ > Listing 5-1 의 ` User ` 구조체 정의에서는 의도적으로
262
+ > ` &str ` 문자열 슬라이스 대신 구조체가 소유권을 갖는 ` String ` 타입을 사용했습니다.
263
+ > 구조체 인스턴스가 유효한 동안 인스턴스 내의
264
+ > 모든 데이터가 유효하도록 만들기 위해서죠 .
265
265
>
266
- > It’s possible for structs to store references to data owned by something else ,
267
- > but to do so requires the use of * lifetimes * , a Rust feature that we’ll
268
- > discuss in Chapter 10. Lifetimes ensure that the data referenced by a struct
269
- > is valid for as long as the struct is. Let’s say you try to store a reference
270
- > in a struct without specifying lifetimes, like this, which won’t work:
266
+ > 참조자를 이용해 구조체가 소유권을 갖지 않는 데이터도 저장할 수는 있지만 ,
267
+ > 이는 10장에서 배울 라이프타임( * lifetime * )을 활용해야 합니다.
268
+ > 라이프타임을 사용하면 구조체가 존재하는 동안에
269
+ > 구조체 내 참조자가 가리키는 데이터의 유효함을 보장받을 수 있기 때문이죠.
270
+ > 만약 라이프타임을 명시하지 않고 참조자를 저장하고자 하면 다음처럼 문제가 발생합니다.
271
271
>
272
272
> <span class =" filename " >Filename: src/main.rs</span >
273
273
>
@@ -289,7 +289,7 @@ itself. We’ll discuss traits in Chapter 10.
289
289
> }
290
290
> ```
291
291
>
292
- > The compiler will complain that it needs lifetime specifiers:
292
+ > 라이프타임이 명시돼야 한다며 컴파일러가 에러를 일으킬 겁니다.
293
293
>
294
294
> ```text
295
295
> error[E0106]: missing lifetime specifier
@@ -305,6 +305,6 @@ itself. We’ll discuss traits in Chapter 10.
305
305
> | ^ expected lifetime parameter
306
306
> ```
307
307
>
308
- > In Chapter 10, we’ll discuss how to fix these errors so you can store
309
- > references in structs, but for now, we’ll fix errors like these using owned
310
- > types like `String` instead of references like `&str` .
308
+ > 위 에러를 해결하여 구조체에 참조자를 저장하는 방법은 10장에서 알아볼 겁니다.
309
+ > 지금 당장은 `&str` 대신 `String` 을 사용함으로써
310
+ > 넘어가도록 하죠 .
0 commit comments