Notice
Recent Posts
Recent Comments
Link
반응형
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 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 |
Tags
- rust
- gjk-epa
- 비동기적
- roslaunch
- narrow-phase
- UV
- remapping
- CMAKE
- convex
- Cargo
- separating axis theorem(sat)
- 데이터분석
- gjk
- subsribe
- unittest
- Topic
- cbindgen
- C++
- CONSTRAINTS
- rospy.spin
- 워크스페이스
- ROS
- gradient accumulation
- plotjuggler
- generic pointer
- corrosion
- mock
- broad-phase
- Turtlesim
- vscode
Archives
- Today
- Total
똑바른 날개
Rust의 scope와 shadowing 본문
반응형
Rust의 변수는 scope를 가지며, 해당 공간안에서만 살아있다. scope는 {}으로 설명된다.
fn main() {
// This binding lives in the main function
let long_lived_binding = 1;
// This is a block, and has a smaller scope than the main function
{
// This binding only exists in this block
let short_lived_binding = 2;
println!("inner short: {}", short_lived_binding);
}
// End of the block
// Error! `short_lived_binding` doesn't exist in this scope
println!("outer short: {}", short_lived_binding);
// FIXME ^ Comment out this line
println!("outer long: {}", long_lived_binding);
}
위의 코드를 실행시켜보면 block밖에서 short_lived_bindg을 호출하면 에러가 발생한다.
이는, block안에서만 살아있던 short_lived_binding이 scope를 빠져나가면서 사라짐을 의미한다.
또한 rust에서 let으로 선언되는 변수는 기본적으로 immutable이지만, shadowing은 가능하다.
아래는 shadowing의 예시이다.
fn main() {
let shadowed_binding = 1;
{
println!("before being shadowed: {}", shadowed_binding);
// This binding *shadows* the outer one
let shadowed_binding = "abc";
println!("shadowed in inner block: {}", shadowed_binding);
}
println!("outside inner block: {}", shadowed_binding);
// This binding *shadows* the previous binding
let shadowed_binding = 2;
println!("shadowed in outer block: {}", shadowed_binding);
}
>>>
before being shadowed: 1
shadowed in inner block: abc
outside inner block: 1
shadowed in outer block: 2
1. 첫번째 출력은 좀더 큰 scope에 있는 shadowed_binding이 출력된다.
2. 다음 scope에 들어가면서, shadowed_binding은 작은 scope에서 shadowing되며, abc로 변한다.(겉에 옷을 입었다고 생각하면 편하다.)
3. 이제 shadowed_binding은 abc로 변한다. 그 뒤 작은 scope를 빠져나오면 abc가 아닌 1로 변한다.(겉에 옷을 변한 것으로 생각)
4. 마지막으로, 같은 영역에서 shadowed_binding은 2가 된다.

반응형
'프로그래밍 > Rust' 카테고리의 다른 글
| Rust설치, Cargo활용 및 유용한 확장(Vscode, IDE) (0) | 2025.09.03 |
|---|---|
| Rust-C++ 통합 : cbindgen과 Collision을 활용한 workflow (0) | 2025.09.02 |
| cbindgen이란? rust -> c++연결을 위한 자동헤더 생성기 (0) | 2025.09.01 |
| Corrosion : Rust와 CMake의 통합 (0) | 2025.09.01 |
| Rust에서의 Dispatch(Static dispatch vs dynamic dispatch) (5) | 2025.07.17 |