When it comes to managing memory, there are two characteristics we’d like from our programing languages:
But these seem to be mutually exclusive: freeing a value while pointers exist to it necessarily leaves those pointers dangling. Almost all major programming languages fall into one of two camps, depending on which of the two qualities they give up on:
The “Safety First” camp uses garbage collection to manage memory, automatically freeing objects when all reachable pointers to them are gone. This eliminates dangling pointers by simply keeping the objects around until there are no pointers to them left to dangle. Almost all modern languages fall in this camp, from Python, JavaScript, and Ruby to Java, C#, and Haskell.
But relying on garbage collection means relinquishing control over exactly when objects get freed to the collector. In general, garbage collectors are surprising beasts, and understanding why memory wasn’t freed when you expected can be a challenge.
The “Control First” camp leaves you in charge of freeing memory. Your program’s memory consumption is entirely in your hands, but avoiding dangling pointers also becomes entirely your concern. C and C++ are the only mainstream languages in this camp.
This is great if you never make mistakes, but evidence suggests that eventually you will. Pointer misuse has been a common culprit in reported security problems for as long as that data has been collected.
Rust는 프로그램이 포인터를 사용하는 방법을 제한함으로써 문제를 해결한다. 이 제한의 효과는 compile time 검사가 프로그램의 메모리 안전 오류 (dangling pointer, 이중해제, 초기화되지 않은 포인터) 가 없는지 확인할 수 있도록 질서를 부여한다. C, C++도 마찬가지이지만, 러스트는 아래 내용이 입증되어 있다.
Using Rust’s carefully designed threading primitives, the rules that ensure your code uses memory correctly also serve to prove that it is free of data races. A bug in a Rust program cannot cause one thread to corrupt another’s data, introducing hard to reproduce failures in unrelated parts of the system. ****The nondeterministic behavior inherent in multithreaded code is isolated to those features designed to handle it—mutexes, message channels, atomic values, and so on—rather than appearing in ordinary memory references. C와 C++의 멀티스레드 코드는 평판이 좋지 않지만, Rust에서는 꽤나 좋은 기능을 제공하고 있다.
이러한 제한이 있어도 Rust 언어는 거의 모든 작업에 유연하며, 이점은 다음과 같다 : 광범위한 메모리 관리 및 동시성 버그를 통해 자기 스타일에 맞게 커스터마이징이 하는 것이 가능하다.
Rust의 규칙 : Rust를 통해 사용자에게 유리하도록 활용하는 법을 배우는 것이 가장 중요한 목표
이번 장에서 설명할 내용