Welcome to Comprehensive Rust ๐ฆ
ํ์ฌ ๊ตฌ๊ธ ์ฌ์ดํธ์ ๋ฒ์ญ ํตํฉ ์์ ์ค์ผ๋ก ํ์ฌ ๋ฒ์ ์ archived ๋์์ต๋๋ค.(23-01-10)
๋์ด์ ์ ๋ฐ์ดํธ๋ ๋์ง ์๊ณ ์ต์ข ๋ฐ์ ๋๋ฉด ์ฌ๋ผ์ง ์์ ์ ๋๋ค.
์์ธํ ์ฌํญ์ ์๋ฌธ์ ์ฐธ์กฐ ํ์ธ์
์ด๊ฒ์ ์๋๋ก์ด๋ ํ์ ์ํด ๊ฐ๋ฐ๋ 4์ผ๊ฐ์ ๋ฌ์คํธ ๊ฐ์ข์ ๋๋ค. ๊ธฐ๋ณธ ๋ฌธ๋ฒ๋ถํฐ ์ ๋๋ฆญ, ์๋ฌ ํธ๋ค๋ง๊ณผ ๊ฐ์ ๊ณ ๊ธ์ฃผ์ ๊น์ง ๋ฌ์คํธ์ ๋ชจ๋ ๊ฒ์ ํฌํจํฉ๋๋ค. ๋ง์ง๋ง ๋ ์๋ ์๋๋ก์ด๋์ ๋ํ ๊ฒ ๊น์ง ๋ค๋ฃน๋๋ค.
This is a four day Rust course developed by the Android team. The course covers the full spectrum of Rust, from basic syntax to advanced topics like generics and error handling. It also includes Android-specific content on the last day.
๊ฐ์๋ ๋น์ ์ด ๋ฌ์คํธ์ ๋ํด์ ์๋ฌด๊ฒ๋ ๋ชจ๋ฅธ๋ค๊ณ ๊ฐ์ ํ๊ณ ์๋์ ๋ชฉํ๋ฅผ ๊ฐ์ง๊ณ ์์ต๋๋ค.
- ๋ฌ์คํธ ๊ตฌ๋ฌธ๊ณผ ์ธ์ด์ ๋ํ ํฌ๊ด์ ์ธ ์ดํด๋ฅผ ์ ๊ณตํฉ๋๋ค.
- ๊ธฐ์กด ํ๋ก๊ทธ๋จ์ ์์ ํ๊ณ ๋ฌ์คํธ์์ ์ ํ๋ก๊ทธ๋จ์ ์์ฑํ ์ ์์ต๋๋ค.
- ์ผ๋ฐ์ ์ธ ๋ฌ์คํธ ๊ด์ฉ๊ตฌ๋ฅผ ๋ณด์ฌ์ค๋๋ค.
The goal of the course is to teach you Rust. We assume you donโt know anything about Rust and hope to:
- Give you a comprehensive understanding of the Rust syntax and language.
- Enable you to modify existing programs and write new programs in Rust.
- Show you common Rust idioms.
4์ผ์ฐจ ๊ฐ์์ ์ฐ๋ฆฌ๋ ์๋์ ๊ฐ์ ์๋๋ก์ด๋ ํน์ ์ ๊ฒ๋ค๋ ์ค๋ช ํฉ๋๋ค.
- ๋ฌ์คํธ์์ Android ๊ตฌ์ฑ ์์๋ฅผ ๊ตฌ์ถ.
- AIDL ์๋ฒ ๋ฐ ํด๋ผ์ด์ธํธ.
- C, C++ ๋ฐ Java์์ ์ํธ ์ด์ฉ์ฑ.
On Day 4, we will cover Android-specific things such as:
- Building Android components in Rust.
- AIDL servers and clients.
- Interoperability with C, C++, and Java.
์ด ๊ณผ์ ์ ๋ฌ์คํธ๋ก ์๋๋ก์ด๋ ์ดํ๋ฆฌ์ผ์ด์ ์ ๊ฐ๋ฐํ๋ ๊ฒ์ ๋ค๋ฃจ๋ ๊ฒ์ด ์๋๋ผ, ์๋๋ก์ด๋ OS์์์ ๋ฌ์คํธ ์ฝ๋ ์์ฑ์ ๋ค๋ฃน๋๋ค.
It is important to note that this course does not cover Android application development in Rust, and that the Android-specific parts are specifically about writing code for Android itself, the operating system.
Non-Goals
๋ฌ์คํธ๋ ๋ช์ผ๋ง์ ๋ชจ๋ ๊ฒ์ ๋ค๋ฃจ๊ธฐ์๋ ๋๋ฌด ํฐ ์ธ์ด์ ๋๋ค. ๊ทธ๋์ ์๋์ ๊ฐ์๊ฒ์ ๋ชฉํ๋ก ํ์ง ์์ต๋๋ค.
Rust is a large language and we wonโt be able to cover all of it in a few days. Some non-goals of this course are:
- ๋น๋๊ธฐ์ ๋ฌ์คํธ ์ฌ์ฉ๋ฒ โ ๊ฐ๋จํ๊ฒ ์ธ๊ธ์ ๋๋ ํ๊ฒ ์ง๋ง ์ข ๋ ์์ธํ ๋ด์ฉ์ Asynchronous Programming in Rust๋ฅผ ์ฐธ์กฐํด์ฃผ์ธ์
- Learn how to use async Rust โ weโll only mention about async Rust when covering traditional concurrency primitives. Please see Asynchronous Programming in Rust instead for details on this topic.
- ๋งคํฌ๋ก๋ฅผ ๊ฐ๋ฐํ๋ ๋ฐฉ๋ฒ. Chapter 19.5 in the Rust Book์ Rust by Example๋ฅผ ์ฐธ์กฐํ์ธ์
- Learn how to develop macros, please see Chapter 19.5 in the Rust Book and Rust by Example instead.
Assumptions
๋ณธ ๊ฐ์ข๋ ๋น์ ์ด ํ๋ก๊ทธ๋๋ฐ ์์ฒด์ ๋ํด์๋ ์๊ณ ์๋ค๊ณ ๊ฐ์ ํฉ๋๋ค. ๋ฌ์คํธ๋ ์ ์ ํ์ ์ธ์ด์ด๋ฉฐ, ๊ฐ์ข์์๋ C์ C++๊ณผ ๋น๊ต, ๋์กฐ๋ฅผ ํตํด ๋ฌ์คํธ๋ฅผ ์ค๋ช ํ ๊ฒ์ ๋๋ค.
The course assumes that you already know how to program. Rust is a statically typed language and we will sometimes make comparisons with C and C++ to better explain or contrast the Rust approach.
๋ง์ผ ๋น์ ์ด ๋์ ํ์ ์ธ์ด(Python์ด๋ JavaScript)๋ก ํ๋ก๊ทธ๋๋ฐ ํ๋ ๋ฐฉ๋ฒ์ ์๊ณ ์๋ค๋ฉด ์ ๋ฐ๋ผ์ฌ ์ ์์ ๊ฒ์ ๋๋ค.
If you know how to program in a dynamically typed language such as Python or JavaScript, then you will be able to follow along just fine too.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์ด๊ฒ์ _speaker note_์ ์์ ์ ๋๋ค. ์ด ๋ถ๋ถ์ ์ด์ฉํด์ ์ถ๊ฐ ์ ๋ณด๋ฅผ ์ ๊ณตํฉ๋๋ค. ์ฃผ๋ก ๊ฐ์์ค์์ ์ ๊ธฐ๋๋ ์ผ๋ฐ์ ์ธ ์ง๋ฌธ์ ๋ํ ๋ต๋ณ๊ณผ ๊ฐ์ฌ๊ฐ ๋ค๋ฃจ์ด์ผ ํ ์ฃผ์ ์์ ์ผ ์ ์์ต๋๋ค.
This is an example of a speaker note. We will use these to add additional information to the slides. This could be key points which the instructor should cover as well as answers to typical questions which come up in class.
์ญ์ฃผ
- ํด๋น๊ธฐ๋ฅ์ ์ ์ฐฝ์ผ๋ก ๋ ธํธ ๋ถ๋ถ์ ๋ฐ๋ก ๋์ฐ๋ ppt ๋ฐํ์ฉ ํ๋ ์ ํ ์ด์ ๊ณผ ์ ์ฌํ ๊ธฐ๋ฅ์ ๋๋ค๋ง ์ญ์ฃผ์์ ์ผ๋ถ hint ๋ฑ์ผ๋ก์ ๊ธฐ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๊ณ ์์ด์ ์๋ฌธ์ speaker note ๊ธฐ๋ฅ์ ์๋์ ์ผ๋ก ๊บผ ๋์ ์ํ์ ๋๋ค.
- ์ ๊ธฐ ์ ๋ชฉ(summary)์ผ๋ก
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
๋ผ๊ณ ๋ ๋ถ๋ถ์ด ํด๋น ๋ฐํ์๋ฃ์ ๋๋ค.
Using Cargo
๋ฌ์คํธ๋ฅผ ์์ํ๋ ค๊ณ ํ๋ฉด ๋น์ ์ ๊ณง Cargo๋ผ๋ ๋ฌ์คํธ ์ํ๊ณ์์ ์ฌ์ฉํ๋ ํ์ค ๋น๋/์คํ ๋๊ตฌ๋ฅผ ๋ง๋ ๊ฒ ์ ๋๋ค. ์ฌ๊ธฐ์๋ ์นด๊ณ ๊ฐ ๋ฌด์์ธ์ง, ๊ทธ๋ฆฌ๊ณ ์นด๊ณ ๊ฐ ๋ ๋์ ์ํ๊ณ์ ์ด๋ป๊ฒ ์ ํฉํ์ง, ๊ทธ๋ฆฌ๊ณ ์ด ๊ต์ก์ ์ด๋ป๊ฒ ์ ํฉํ์ง์ ๋ํ ๊ฐ๋ตํ ๊ฐ์๋ฅผ ์ ๊ณตํ๊ณ ์ ํฉ๋๋ค.
When you start reading about Rust, you will soon meet Cargo, the standard tool used in the Rust ecosystem to build and run Rust applications. Here we want to give a brief overview of what Cargo is and how it fits into the wider ecosystem and how it fits into this training.
Debian์ด๋ Ubuntu์์ cargo์ rust-src๋ฅผ ์๋ ์ปค๋งจ๋๋ก ์ค์นํฉ๋๋ค.
On Debian/Ubuntu, you can install Cargo and the Rust source with
$ sudo apt install cargo rust-src
VS Code์์ ์์ ํ๋ ๊ฑธ ์ถ์ฒ ๋๋ฆฝ๋๋ค. rust-analyzer ํ์ฅ์ ํตํด ์ ์ ์ด๋ ๋ฑ ๊ฐ๋ฐ์ ๋์ ๋ฐ์ ์ ์์ต๋๋ค.(๋๋ ๋ค๋ฅธ IDE๋ ํธ์ง๊ธฐ๋ฅผ ์ฌ์ฉํด๋ ๋ฌด๋ฐฉํฉ๋๋ค.)
This will allow rust-analyzer to jump to the definitions. We suggest using VS Code to edit the code (but any LSP compatible editor works)
์ฐธ๊ณ ๋ก, ๋ง์ฝ ๊ฐ๋ฅํ๋ค๋ฉด rustup๊ณผ ๊ฐ์ ๋ฌ์คํธ ์ํ๊ณ ํด์ ํตํ ์ค์น๋ฅผ ์ถ์ฒ๋๋ฆฝ๋๋ค.
As a sidenote: if you have the access/capability to do so, itโs recommended to install Rustโs tooling via rustup since itโs better integrated with the rest of the ecosystem.
The Rust Ecosystem
๋ฌ์คํธ์ ์ํ๊ณ๋ ์ฌ๋ฌ๊ฐ์ง ๋๊ตฌ๋ค๋ก ๊ตฌ์ฑ๋์ด ์์ผ๋ฉฐ, ๊ทธ ์ค ์ค์ํ ๊ฒ๋ค์ ์๋์ ๊ฐ์ต๋๋ค.
The Rust ecosystem consists of a number of tools, of which the main ones are:
rustc
:.rs
ํ์ฅ์ ํ์ผ์ ๋ฐ์ด๋๋ฆฌ ํน์ ๋ค๋ฅธ ์ค๊ฐ์ ํ์์ผ๋ก ๋ณํํด์ฃผ๋ Rust ์ปดํ์ผ๋ฌ์ ๋๋ค.
rustc
: the Rust compiler which turns.rs
files into binaries and other intermediate formats.
cargo
: ๋ฌ์คํธ ์ข ์์ฑ ๊ด๋ฆฌ์ ๋ฐ ๋น๋๋๊ตฌ ์ ๋๋ค. https://crates.io์์ ํธ์คํ ๋๋ ์ฌ๋ฌ ์ข ์์ฑ์ ๋ค์ด๋ก๋ํ๊ณrustc
๊ฐ ๋น์ ์ ํ๋ก์ ํธ๋ฅผ ๋น๋ํ ๋ ์ด๋ฅผ ์ ๋ฌํฉ๋๋ค. ๋ํ ์ ๋ ํ ์คํธ๋ฅผ ์คํํ๋ ํ ์คํธ ํด์ ๋ด์ฅํ๊ณ ์์ต๋๋ค.
cargo
: the Rust dependency manager and build tool. Cargo knows how to download dependencies hosted on https://crates.io and it will pass them torustc
when building your project. Cargo also comes with a built-in test runner which is used to execute unit tests.
rustup
: ๋ฌ์คํธ ํด์ฒด์ธ ์ค์น ํ๋ก๊ทธ๋จ ๋ฐ ์ ๋ฐ์ดํธ ํ๋ก๊ทธ๋จ. ์ด ๋๊ตฌ๋ ์ ๋ฒ์ ์ ๋ฌ์คํธ๊ฐ ์ถ์๋ ๋rustc
๋ฐcargo
์ค์นํ๊ณ ์ ๋ฐ์ดํธํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค. ๋ํrustup
์ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋ํ ๋ฌธ์๋ฅผ ๋ค์ด๋ก๋ํ ์๋ ์์ต๋๋ค. ํ ๋ฒ์ ์ฌ๋ฌ ๋ฒ์ ์ ๋ฌ์คํธ๋ฅผ ์ค์นํ ์ ์์ผ๋ฉฐrustup
์ ํตํด ํ์์ ๋ฐ๋ผ ์ด๋ค ๋ฒ์ ์ ์ ํํ ์ ์์ต๋๋ค
rustup
: the Rust toolchain installer and updater. This tool is used to install and updaterustc
andcargo
when new versions of Rust is released. In addition,rustup
can also download documentation for the standard library. You can have multiple versions of Rust installed at once andrustup
will let you switch between them as needed.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
ํคํฌ์ธํธ:
- ๋ฌ์คํธ๋ 6์ฃผ๋ง๋ค ์๋ก์ด ๋ฆด๋ฆฌ์ฆ๊ฐ ๋ฐํ๋๋ฉฐ ์ด์ ๋ฆด๋ฆฌ์ฆ์์ ํธํ์ฑ์ ์ ์งํ๊ณ ์์ต๋๋ค.
- ๋ฆด๋ฆฌ์ฆ๋ 3๊ฐ์ง ๋ฒ์ ์ผ๋ก ์ ๊ณต๋ฉ๋๋ค: โstableโ, โbetaโ ๊ทธ๋ฆฌ๊ณ โnightlyโ.
- ์๋ก์ด ๊ธฐ๋ฅ์ โnightlyโ -> โbetaโ -(6์ฃผ ํ)-> โstableโ ๋ก ๋ณ๊ฒฝ๋ฉ๋๋ค.
- ๋ฌ์คํธ๋ editions์ผ๋ก ์ผ๋ก ์งํ๋ฉ๋๋ค: ํ์ฌ๋ Rust 2021 ์๋์
์
๋๋ค. ๊ทธ์ ์๋ Rust 2015์ Rust 2018์
๋๋ค.
- ์๋์ ์ ์ด์ ์๋์ ๊ณผ ํธํ์ด ๋์ง ์์ ์ ์์ต๋๋ค.
- ํ๋ก๊ทธ๋จ ๋ถ๊ดด๋ฅผ ๋ฐฉ์งํ๊ธฐ ์ํด ์๋์
์ ์ต์
์
๋๋ค.:
Cargo.toml
์์ ์ง์ ํ ์ ์์ต๋๋ค. - ์ํ๊ณ๊ฐ ๋ถ์ด๋๋ ๊ฒ์ ๋ง๊ธฐ ์ํด ๋ฌ์คํธ ์ปดํ์ผ๋ฌ๋ ๋ค๋ฅธ ์๋์ ์์ ์์ฑ๋ ์ฝ๋์ ํผํฉ์ด ๊ฐ๋ฅํฉ๋๋ค.
Key points:
Rust has a rapid release schedule with a new release coming out every six weeks. New releases maintain backwards compatibility with old releases โ plus they enable new functionality.
There are three release channels: โstableโ, โbetaโ, and โnightlyโ.
New features are being tested on โnightlyโ, โbetaโ is what becomes โstableโ every six weeks.
Rust also has editions: the current edition is Rust 2021. Previous editions were Rust 2015 and Rust 2018.
The editions are allowed to make backwards incompatible changes to the language.
To prevent breaking code, editions are opt-in: you select the edition for your crate via the
Cargo.toml
file.To avoid splitting the ecosystem, Rust compilers can mix code written for different editions.
Code Samples in This Training
์ด ๊ต์ก์ ์ํด ์ฐ๋ฆฌ๋ ๋น์ ์ ๋ธ๋ผ์ฐ์ ์์ ์คํ๋ ์ ์๋ ์์ ๋ฅผ ์ ๊ณตํ ๊ฒ์ ๋๋ค. ์ด๋ ๊ฒ ํ๋ฉด ์ค์น๊ฐ ํจ์ฌ ์ฌ์์ง๊ณ ๋ชจ๋ ์ฌ์ฉ์๊ฐ ์ผ๊ด๋ ํ๊ฒฝ์ ์ฌ์ฉํ ์ ์๊ฒ๋ฉ๋๋ค.
For this training, we will mostly explore the Rust language through examples which can be executed through your browser. This makes the setup much easier and ensures a consistent experience for everyone.
์นด๊ณ (cargo)๋ฅผ ์ค์นํ๋ ๊ฒ์ ์ฌ์ ํ ์ข์ต๋๋ค. ์ด ๊ฒ์ ๋น์ ์ ์ฐ์ต์ ๋ ์ฝ๊ฒ ๋ง๋ค์ด ์ค๋๋ค. ๋ง์ง๋ง ๋ ๊ฐ์์์ ๋น์ ์ด Cargo๋ฅผ ํ์๋ก ํ๋ ์์กด์ฑ์ ๊ฐ์ง๊ณ ์์ ํ๋ ๊ฒฝํ์ ํ ๊ฒ์ ๋๋ค.
Installing Cargo is still encouraged: it will make it easier for you to do the exercises. On the last day, we will do a larger exercise which shows you how to work with dependencies and for that you need Cargo.
์ด ๊ณผ์ ์ ์ฝ๋ ๋ธ๋ก๋ค์ ์ ๋ถ ๋ํํ์ผ๋ก ๊ตฌ์ฑ๋ ์์ต๋๋ค.
The code blocks in this course are fully interactive:
fn main() { println!("Edit me!"); }
์ฝ๋ ๋ธ๋ก์ ํฌ์ปค์ค๋ฅผ ๋๊ณ Ctrl-Enter๋ฅผ ๋๋ฌ ์คํํด ๋ณผ ์ ์์ต๋๋ค.
You can use Ctrl-Enter to execute the code when focus is in the text box.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
๊ฐ์์์ ๋๋ถ๋ถ์ ์ฝ๋ ์ํ์ ์์ ๊ฐ์ด ์์ ํ ์ ์์ง๋ง ์ผ๋ถ ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ ์ด์ ๋ก ์์ ํ ์ ์์ต๋๋ค:
- ์ ๋ ํ ์คํธ๋ ๋ด์ฅ ํ๋ ์ด๊ทธ๋ผ์ด๋์์ ์คํ์ด ์๋ฉ๋๋ค. ์ธ๋ถ ํ๋ ์ด๊ทธ๋ผ์ด๋ ์ฌ์ดํธ์ ๋ถ์ฌ๋ฃ์ด ํ ์คํธ๋ฅผ ์คํํ์๊ธฐ ๋ฐ๋๋๋ค.
- ํ์ด์ง์์ ์ด๋ํ๋ฉด ๋ด์ฅ๋ ํ๋ ์ด๊ทธ๋ผ์ด๋๋ state๋ฅผ ์์ต๋๋ค. ๋ฐ๋ผ์ ๋ก์ปฌ ํ๊ฒฝ์ด๋ ์ธ๋ถ ํ๋ ์ด๊ทธ๋ผ์ด๋ ์ฌ์ดํธ์์ ์ฐ์ต๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๊ฒ์ด ์ข์ต๋๋ค.
Most code samples are editable like shown above. A few code samples are not editable for various reasons:
The embedded playgrounds cannot execute unit tests. Copy-paste the code and open it in the real Playground to demonstrate unit tests.
The embedded playgrounds lose their state the moment you navigate away from the page! This is the reason that the students should solve the exercises using a local Rust installation or via the Playground.
์ญ์ฃผ:
- ์ ๋ฐ ๋ธ๋ก๋ค์ ๊ณผ์ ์ฌ์ดํธ์์ ์คํ๋ฉ๋๋ค.
- ์์ค๋จ(md)์์ ์คํ์๋ฉ๋๋ค(..)
Running Code Locally with Cargo
๋ง์ฝ ๋น์ ์ด ๋ก์ปฌ ์์คํ
์์ ์ฝ๋๋ฅผ ์คํํด๋ณด๋ ค๋ฉด ๋จผ์ ๋ฌ์คํธ๋ฅผ ์ค์นํด์ผ ํฉ๋๋ค.
Rust Book์ ์ง์นจ์ ๋ฐ๋ผ rustc
์ cargo
๋ฅผ ํจ๊ป ์ค์น ํ์ธ์
์ค์น ํ ์๋ ์ปค๋งจ๋๋ฅผ ํตํด ๊ฐ ์ํ๊ณ ํด์ ๋ฒ์ ์ ํ์ธ ํ ์ ์์ต๋๋ค.
If you want to experiment with the code on your own system, then you will need to first install Rust. Do this by following the instructions in the Rust Book. This should give you a working
rustc
andcargo
. At the time of writing, the latest stable Rust release has these version numbers:
% rustc --version
rustc 1.61.0 (fe5b13d68 2022-05-18)
% cargo --version
cargo 1.61.0 (a028ae4 2022-04-29)
์ ์์ ์ผ๋ก ์ค์น๊ฐ ๋์์ผ๋ฉด ๊ฐ์์ ์ฝ๋ ๋ธ๋ก์ค ํ๋๋ฅผ ์๋ ๋จ๊ณ๋ฅผ ๋ฐ๋ผ ๋ก์ปฌ์์ ์คํํ ์ ์์ต๋๋ค.
With this is in place, then follow these steps to build a Rust binary from one of the examples in this training:
- ์์ ๋ธ๋ก์ ์๋ โCopy to clipboardโ๋ฒํผ์ ํด๋ฆญํด์ ๋ณต์ฌํฉ๋๋ค.
- Click the โCopy to clipboardโ button on the example you want to copy.
- shell์์
cargo new exercise
๋ฅผ ์ ๋ ฅํด์ ์๋ก์ดexercise/
ํด๋๋ฅผ ๋ง๋ญ๋๋ค.
- Use
cargo new exercise
to create a newexercise/
directory for your code:
$ cargo new exercise
Created binary (application) `exercise` package
exercise/
ํด๋๋ก ์ด๋ํ ํ,cargo run
์ปค๋งจ๋๋ก ์ฝ๋๋ฅผ ์คํํฉ๋๋ค.
- Navigate into
exercise/
and usecargo run
to build and run your binary:
$ cd exercise
$ cargo run
Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)
Finished dev [unoptimized + debuginfo] target(s) in 0.75s
Running `target/debug/exercise`
Hello, world!
- ๋ณด์ผ๋ฌํ๋ ์ดํธ ์ฝ๋๋
src/main.rs
์ ์์ฑํฉ๋๋ค. ์๋ฅผ ๋ค์ด ์ด์ ํ์ด์ง์ ์์ค๋ฅผ ์๋์ ๊ฐ์ดsrc/main.rs
์ ์์ฑํฉ๋๋ค.
- Replace the boiler-plate code in
src/main.rs
with your own code. For example, using the example on the previous page, makesrc/main.rs
look like
fn main() { println!("Edit me!"); }
cargo run
์ปค๋งจ๋๋ก ์์ค๋ฅผ ๋น๋ํ๊ณ ์คํํฉ๋๋ค.
- Use
cargo run
to build and run your updated binary:
$ cargo run
Compiling exercise v0.1.0 (/home/mgeisler/tmp/exercise)
Finished dev [unoptimized + debuginfo] target(s) in 0.24s
Running `target/debug/exercise`
Edit me!
cargo check
์ปค๋งจ๋๋ ๋น ๋ฅด๊ฒ ๋น์ ์ ํ๋ก์ ํธ์์ ์๋ฌ๋ฅผ ํ์ธํ ์ ์์ต๋๋ค.cargo build
๋ ์คํ์์ด ์์ค๋ฅผ ์ปดํ์ผ ํฉ๋๋ค. ์ด ๊ฒฝ์ฐ์target/debug/
ํด๋์์ output์ ํ์ธ ํ ์ ์์ต๋๋ค.cargo build --release
์ปค๋งจ๋๋ ๋ฆด๋ฆฌ์ฆ ๋ฒ์ ์ ์ต์ ํ๋ output์ผ๋ก ์ปดํ์ผํ๋ฉฐtarget/release/
ํด๋์์ ํ์ธ ํ ์ ์์ต๋๋ค.
- Use
cargo check
to quickly check your project for errors, usecargo build
to compile it without running it. You will find the output intarget/debug/
for a normal debug build. Usecargo build --release
to produce an optimized release build intarget/release/
.
Cargo.toml
ํ์ผ์๋ ๋น์ ์ ํ๋ก์ ํธ์ ์ฌ์ฉํ๋ ์์กด์ฑ ํจํค์ง๋ฅผ ์ถ๊ฐํ ์ ์์ต๋๋ค.cargo
์ปค๋งจ๋๋ฅผ ์คํํ๋ฉด ์๋์ผ๋ก ํ๋ก์ ํธ์ ์์กด์ฑ ํจํค์ง๋ฅผ ๋ค์ด๋ก๋, ์ปดํ์ผ ํด์ค๋๋ค.
- You can add dependencies for your project by editing
Cargo.toml
. When you runcargo
commands, it will automatically download and compile missing dependencies for you.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
๊ฐ์ ์ฐธ์ฌ์๋ค์ด ์นด๊ณ ๋ฅผ ์ค์นํ๊ณ ๋ก์ปฌ ํธ์ง๊ธฐ๋ฅผ ์ด์ฉํ๋ ๊ฒ์ ์ถ์ฒํฉ๋๋ค. ์ด ํธ์ด ์ข ๋ ์ ์์ ์ธ ๊ฐ๋ฐํ๊ฒฝ์ ๊ฐ์ถ ์ ์์ต๋๋ค.
Try to encourage the class participants to install Cargo and use a local editor. It will make their life easier since they will have a normal development environment.
์ญ์ฃผ:
- (ํน์๋ชฐ๋ผ ๊ธฐ๋กํ์๋ฉด)ํ์ต์ฉ ํด๋๋ฅผ ํ๋ ๋ง๋ค๊ณ ๊ฑฐ๊ธฐ์ ์ง์์ฌํญ์ ์คํํฉ๋๋ค.
Course Structure
๊ฐ์๋ ๋น ๋ฅธ ์๋๋ก ์งํ๋๋ฉด ๋ค์ 3,4์ผ๋์ ๋ง์ ๋ฒ์์ ๋ถ๋ถ์ ๋ค๋ฃน๋๋ค.
The course is fast paced and we will cover a lot of ground over the next 3โ4 days:
- 1์ผ์ฐจ: ๋ฌ์คํธ ๊ธฐ๋ณธ, ์์ ๊ถ(ownership)๊ณผ ๋น๋ฆผ(borrow) ์ฒดํฌ.
- 2์ผ์ฐจ: ๋ณตํฉ ๋ฐ์ดํฐ ์ ํ, ํจํด ๋งค์นญ, ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ
- 3์ผ์ฐจ: ํธ๋ ์(traits)๊ณผ ์ ๋๋ฆญ(generics), ์๋ฌ ํธ๋ค๋ง(์ค๋ฅ ์ฒ๋ฆฌ), ํ ์คํธ, ์์ ํ์ง ์์ ๋ฌ์คํธ.
- 4์ผ์ฐจ: ๋ฌ์คํธ์ ๋์์ฑ ๋ฐ ๋ค๋ฅธ ์ธ์ด์์ ์ํธ ์ด์ฉ์ฑ
- Day 1: Basic Rust, ownership and the borrow checker.
- Day 2: Compound data types, pattern matching, the standard library.
- Day 3: Traits and generics, error handling, testing, unsafe Rust.
- Day 4: Concurrency in Rust and interoperability with other languages
4์ผ์ฐจ์ ์ฐ์ต: ๋ฌ์คํธ ํ๋ก์ ํธ์์ C/C++๋ก ์์ฑ๋ ์ฝ๋๋ฅผ ์ด์ ํด์ ์ฐ๊ฒฐํ๋ ค๊ณ ํ๋ค๋ฉด ์ข ์์ฑ์ด ์ ์ ์๋ก ์ข์ต๋๋ค. ์ฝ๋๋ฅผ ๊ตฌ๋ฌธ๋ถ์ํ๋ ๊ฒ์ด ์ด์์ ์ ๋๋ค.
Exercise for Day 4: Do you interface with some C/C++ code in your project ๋ฉด which we could attempt to move to Rust? The fewer dependencies the better. Parsing code would be ideal.
Format
๊ฐ์๋ ๋ํ์์ด๋ฉฐ ๋น์ ์ ์ง๋ฌธ์ด ๋ฌ์คํธ ํํ์ ์ด๋ ๊ฒ์ ๋๋ค!
The course is interactive and your questions will drive our exploration of Rust!
- ์ง๋ฌธ์ด ์๊ธฐ๋ฉด ์ง๋ฌธํด์ฃผ์ธ์
- ํ ๋ก ์ ๋งค์ฐ ๊ถ์ฅ๋ฉ๋๋ค!
- ๊ฐ์์ ์๋ฃ๋ ์ฐธ๊ณ ์๋ฃ์ผ ๋ฟ์ผ๋ก ๊ฑด๋๋ ์ ์์ต๋๋ค.
- Please ask questions when you get them, donโt save them to the end.
- Discussions are very much encouraged!
- We will likely talk about things ahead of the slides.
- The slides are just a support and we are free to skip them as we like.
Welcome to Day 1
๊ฐ์์ ์ฒซ ๋ ์ ๋๋ค. ์ฐ๋ฆฌ๋ ์ค๋ ๋ง์ ๋ถ๋ถ์ ๋ค๋ฃฐ ๊ฒ์ ๋๋ค.
This is the first day of Comprehensive Rust. We will cover a lot of ground today:
- ๋ฌ์คํธ ๊ธฐ๋ณธ ๋ฌธ๋ฒ: ๋ณ์, ์ค์นผ๋ผ / ๋ณตํฉ ํ์ , ์ด๊ฑฐํ, ๊ตฌ์กฐ์ฒด, ์ฐธ์กฐํ, ํจ์์ ๋ฉ์๋.
- Basic Rust syntax: variables, scalar and compound types, enums, structs, references, functions, and methods.
- ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ: ์คํ๊ณผ ํ, ์๋ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ, ์ค์ฝํ(๋ฒ์)๊ธฐ๋ฐ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ, ๊ฐ๋น์ง ์ปฌ๋ ์ (GC)
- Memory management: stack vs heap, manual memory management, scope-based memory management, and garbage collection.
- ์์ ๊ถ: ์๋ฏธ ์ด๋, ๋ณต์ฌ์ ๋ณต์ , ๋น๋ฆผ, ์๋ช .
- Ownership: move semantics, copying and cloning, borrowing, and lifetimes.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์ฒซ ๋ ๊ฐ์์ ๋ชฉํ๋ ๋น๋ฆผ ํ์ธ ๋ฑ์ ๋ํด ๋งํ ์ ์์ ๋งํผ์ ๋ฌ์คํธ์ ๋ํด ๋ณด์ฌ์ฃผ๋ ๊ฒ์ ๋๋ค. ๋ฌ์คํธ๊ฐ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ค๋ฃจ๋ ๋ฐฉ์์ ์ฃผ์ํ ํน์ง์ด๋ฉฐ ์ฐ๋ฆฌ๋ ํ์๋ค์๊ฒ ์ฐ์ ํด์ ๋ณด์ฌ์ฃผ๋ ค๊ณ ํฉ๋๋ค.
๋ง์ฝ ๋น์ ์ด ๊ต์คํ๊ฒฝ์์ ๊ฐ๋ฅด์น๊ณ ์๋ค๋ฉด, ์ด ๊ณณ์ ์ผ์ ์ ๊ฒํ ํ๊ธฐ ์ข์ ์ฅ์์ ๋๋ค. ์ฐ๋ฆฌ๋ ํ๋ฃจ์ ๊ฐ์๋ฅผ ์ฌ๋ผ์ด๋์ ๋ฐ๋ผ์ ๋ ๋ถ๋ถ์ผ๋ก ๋๋๋ ๊ฒ์ ์ถ์ฒํฉ๋๋ค.
- ์ค์ : 9:00 to 12:00,
- ์คํ: 13:00 to 16:00. ๋ฌผ๋ก ํ์์ ๋ฐ๋ผ ์กฐ์ ํ ์ ์์ต๋๋ค. ๊ฐ์ ์ค๊ฐ์ ์ฌ๋์๊ฐ์ ๋ฃ๋๊ฑธ ๋ถํ๋๋ฆฝ๋๋ค.
The idea for the first day is to show just enough of Rust to be able to speak about the famous borrow checker. The way Rust handles memory is a major feature and we should show students this right away.
If youโre teaching this in a classroom, this is a good place to go over the schedule. We suggest splitting the day into two parts (following the slides):
- Morning: 9:00 to 12:00,
- Afternoon: 13:00 to 16:00. You can of course adjust this as necessary. Please make sure to include breaks, we recommend a break every hour!
What is Rust?
๋ฌ์คํธ๋ 2015๋ 1.0์ผ๋ก ๋ฆด๋ฆฌ์ฆ๋ ์๋ก์ด ํ๋ก๊ทธ๋จ ์ธ์ด์ ๋๋ค.
Rust is a new programming language which had its 1.0 release in 2015:
- ๋ฌ์คํธ๋ C++๊ณผ ๋น์ทํ ์ญํ ์ ํ๋ ์ ์ ์ปดํ์ผ ์ธ์ด์
๋๋ค.
rustc
๋ LLVM์ ๋ฐฑ์๋๋ก ์ฌ์ฉํฉ๋๋ค.
- ๋ฌ์คํธ๋ ๋ค์ํ ํ๋ซํผ๊ณผ ์ํคํ
์ณ๋ฅผ ์ง์ํฉ๋๋ค.
- x86, ARM, WebAssembly, โฆ
- Linux, Mac, Windows, โฆ
- ๋ฌ์คํธ๋ ๋์ ๋ฒ์์ ์ฅ์น์ ์ ์ฉ๋ ์ ์์ต๋๋ค.
- ํ์จ์ด์ ๋ถํธ๋ก๋(์๋ฒ ๋๋)
- ์ค๋งํธ ๋์คํ๋ ์ด
- ์ค๋งํธํฐ
- ๋ฐ์คํฌํ
- ์๋ฒ
- Rust is a statically compiled language in a similar role as C++
rustc
uses LLVM as its backend.- Rust supports many platforms and architectures:
- x86, ARM, WebAssembly, โฆ
- Linux, Mac, Windows, โฆ
- Rust is used for a wide range of devices:
- firmware and boot loaders,
- smart displays,
- mobile phones,
- desktops,
- servers.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
๋ฌ์คํธ๋ C++๊ณผ ๋์ผํ ์์ญ์์ ์ฌ์ฉ๋ฉ๋๋ค.
- ๋์ ์ ์ฐ์ฑ
- ๋์ ๋ ๋ฒจ ์์ค์ ์ ์ด
- ํด๋ํฐ๊ณผ ๊ฐ์ ๋งค์ฐ ์ ํ๋ ์ฅ์น๋ก ์ค์ผ์ผ ๋ค์ด ๊ฐ๋ฅ.
Rust fits in the same area as C++:
- High flexibility.
- High level of control.
- Can be scaled down to very constrained devices like mobile phones.
Hello World!
๊ฐ์ฅ ๊ฐ๋จํ ๋ฌ์คํธ ํ๋ก๊ทธ๋จ์ผ๋ก ๊ณ ์ ์ ์ธ Hello World ์ถ๋ ฅ ํ๋ก๊ทธ๋จ์ ์์ฑํด ๋ณด๊ฒ ์ต๋๋ค.
Let us jump into the simplest possible Rust program, a classic Hello World program:
fn main() { println!("Hello ๐!"); }
์ ์์ค์์ ์ ์ ์๋ ๊ฒ:
- ํจ์๋
fn
์ผ๋ก ์ ์ธ๋ฉ๋๋ค. - C/C++๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก ์ค๊ดํธ
{}
๋ก ๋ธ๋ก์ ํ์ํฉ๋๋ค. main
ํจ์๋ ํ๋ก๊ทธ๋จ ์ง์ ์ ์ ๋๋ค.- ๋ฌ์คํธ๋ ์์์ ์ธ ๋งคํฌ๋ก๋ฅผ ๊ฐ์ง๊ณ ์์ต๋๋ค.
println!
๋ ๊ทธ ์์์ ๋๋ค. - ๋ฌ์คํธ์ ๋ฌธ์์ด์ UTF-8๋ก ์ธ์ฝ๋ฉ๋๋ฉฐ ์ด๋ชจ์ง์ ๊ฐ์ ์ ๋์ฝ๋ ๋ฌธ์๋ฅผ ํฌํจํ ์ ์์ต๋๋ค.
What you see:
- Functions are introduced with
fn
.- Blocks are delimited by curly braces like in C and C++.
- The
main
function is the entry point of the program.- Rust has hygienic macros,
println!
is an example of this.- Rust strings are UTF-8 encoded and can contain any Unicode character.
์ญ์ฃผ
- ๋งคํฌ๋ก: ๋ค๋ฅธ ์ฝ๋๋ฅผ ์์ฑํ๋ ์ฝ๋์ ๋๋ค(meta-programming). ๋ฐํ์์ด ์๋ ์ปดํ์ผ ์ ์ ๋์น ์์ ์ด ์ด๋ค์ง๋๋ฐ C๊ณ์ด์ #define ๋ฌธ๋ฒ์ ์๊ฐํ์๋ฉด ๋ฉ๋๋ค.
- ์์์ ์ธ ๋งคํฌ๋ก(hygienic macros, ์ํค)๋ ์๋ณ์๊ฐ ๊ฒน์น์ง ์์์ด ๋ณด์ฅ๋๋ ๋งคํฌ๋กโฆ ๋ผ๋๋ฐ ์ผ๋จ์ ๊ทธ๋ ๊ตฌ๋ํ๊ณ ์งํ
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์ด ์ฌ๋ผ์ด๋๋ ํ์๋ค์ด ๋ฌ์คํธ ์ฝ๋๋ฅผ ํธํ๊ฒ ๋ณผ ์ ์๋๋ก ์ ๋ํฉ๋๋ค. 4์ผ๋์ ๋ง์ ์์ ์ฝ๋๋ฅผ ๋ณผ ๊ฒ์ด๋ฏ๋ก ์น์ํ๊ณ ๊ฐ๋จํ ์ฝ๋๋ถํฐ ์์ํฉ๋๋ค.
ํคํฌ์ธํธ:
- ๋ฌ์คํธ๋ C/C++/Java์ ๊ฐ์ ์ ํต์ ์ธ ๋ค๋ฅธ ์ธ์ด๋ค๊ณผ ๋งค์ฐ ์ ์ฌํฉ๋๋ค. ํ์์ ์ด๊ณ ์ ๋์ ์ผ๋ก ํ์ํ์ง ์๋ ํ ์๋ก์ด ๊ฒ(๋ฌธ๋ฒ)์ ์ถ๊ฐํ์ง ์์ต๋๋ค.
- ๋ฌ์คํธ๋ ์ ๋์ฝ๋์ ๊ฐ์ ๊ฒ๋ค์ ์ ๋ถ ์ง์ํ๋ ํ๋์ ์ธ ์ธ์ด์ ๋๋ค.
- ๋ฌ์คํธ๋ ์ธ์์ ์๊ฐ ๋ง์ ์ํฉ์ ๋ํด์ ๋งคํฌ๋ก๋ฅผ ์ฌ์ฉํฉ๋๋ค. (no function overloading).
This slide tries to make the students comfortable with Rust code. They will see a ton of it over the next four days so we start small with something familiar.
Key points:
Rust is very much like other languages in the C/C++/Java tradition. It is imperative (not functional) and it doesnโt try to reinvent things unless absolutely necessary.
Rust is modern with full support for things like Unicode.
Rust uses macros for situations where you want to have a variable number of arguments (no function overloading).
Small Example
๋ฌ์คํธ๋ก ์์ฑ๋ ์์ ์์ ์ ๋๋ค.
Here is a small example program in Rust:
fn main() { // ํ๋ก๊ทธ๋จ ์ง์ ์ (Program entry point) let mut x: i32 = 6; // ๊ฐ๋ณ ๋ณ์ ํ ๋น(Mutable variable binding) print!("{x}"); // printf์ ๊ฐ์ ์ถ๋ ฅ ๋งคํฌ๋ก(Macro for printing, like printf) while x != 1 { // ํํ์์๋ ๊ดํธ ์์(No parenthesis around expression) if x % 2 == 0 { // ์ํ์ ๊ธฐํธ๋ ๋ค๋ฅธ์ธ์ด์ ์ ์ฌ(Math like in other languages) x = x / 2; } else { x = 3 * x + 1; } print!(" -> {x}"); } println!(); }
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์ด ์ฝ๋๋ ์ฝ๋ผ์ธ ์ถ์ธก(Collatz conjecture)์ผ๋ก ๊ตฌํ๋ฉ๋๋ค:
๋ฐ๋ณต๋ฌธ์ด ์ธ์ ๋ ์ข
๋ฃ์กฐ ๊ฒ์ด๋ผ๊ณ ๋ฏฟ์ง๋ง ์ฆ๋ช
๋ ๊ฒ์ ์๋๋๋ค. ์ฝ๋๋ฅผ ์์ ํ๊ณ ์คํํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค.
ํคํฌ์ธํธ:
- ๋ชจ๋ ๋ณ์๊ฐ ์ ์ ์ผ๋ก ์
๋ ฅ๋จ์ ์ค๋ช
ํฉ๋๋ค.
i32
๋ฅผ ์ญ์ ํ์ฌ ์ ํ ์ถ๋ก ์ ์ ๋ฐํด ๋ณผ ์ ์์ต๋๋ค.i32
๋์i8
๋ก ๋ณ๊ฒฝํ์ฌ ๋ฐํ์ ์ค๋ฒํ๋ก๋ฅผ ์ ๋ฐํด ๋ณผ ์ ์์ต๋๋ค. let mut x
๋ฅผlet x
๋ก ์์ ํ์ฌ ์ปดํ์ผ ์ค๋ฅ์ ๋ํด ํ ๋ก ํฉ๋๋ค.- ์ธ์๊ฐ ํฌ๋งท ๋ฌธ์์ด๊ณผ ์ผ์นํ์ง ์๋ ๊ฒฝ์ฐ
print!
์์์ ์ปดํ์ผ ์ค๋ฅ๊ฐ ๋ฐ์ํจ์ ์ธ๊ธํ๋ ๊ฒ๋ ์ข์ต๋๋ค. - ๋จ์ผ ๋ณ์๋ณด๋ค ๋ณต์กํ ์์ ์ธ์ํ๋ ค๋ฉด {}์(๋ฅผ) ์๋ฆฌ ํ์์๋ก ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ๋ณด์ฌ ์ค๋๋ค.
- ํ์๋ค์๊ฒ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋ณด์ฌ์ฃผ๊ณ , ๋ฏธ๋ ์ธ์ด ํ์์ ๊ท์น์ด ์๋ std::fmt๋ฅผ ๊ฒ์ํ๋ ๋ฐฉ๋ฒ์ ๋ณด์ฌ์ค๋๋ค. ํ์๋ค์ด ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์์ ๊ฒ์ํ๋ ๊ฒ์ ์ต์ํด์ง๋ ๊ฒ์ด ์ค์ํฉ๋๋ค.
The code implements the Collatz conjecture: it is believed that the loop will always end, but this is not yet proved. Edit the code and play with different inputs.
Key points:
- Explain that all variables are statically typed. Try removing
i32
to trigger type inference. Try withi8
instead and trigger a runtime integer overflow. - Change
let mut x
tolet x
, discuss the compiler error. - Show how
print!
gives a compilation error if the arguments donโt match the format string. - Show how you need to use
{}
as a placeholder if you want to print an expression which is more complex than just a single variable. - Show the students the standard library, show them how to search for
std::fmt
which has the rules of the formatting mini-language. Itโs important that the students become familiar with searching in the standard library.
Why Rust?
๋ฌ์คํธ๋ง์ ๋ ํนํ ์ธ์ผ์ฆ ํฌ์ธํธ(์ฅ์ ):
- ์ปดํ์ผ ์ ๋ฉ๋ชจ๋ฆฌ ์์
- ์ ์๋์ง ์์ ๋ฐํ์ ๋์์ด ์์ต๋๋ค.
- ๋ชจ๋ํ ์ธ์ด์ ํน์ง
Some unique selling points of Rust:
- Compile time memory safety.
- Lack of undefined runtime behavior.
- Modern language features.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
๊ฐ์ ์ฐธ์ฌ์๋ค์๊ฒ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด ์ฌ์ฉ ๊ฒฝํ์ ๋ฌผ์ด๋ณด์๊ธฐ ๋ฐ๋๋๋ค. ๊ฒฝํ์ ๋ฐ๋ผ ๋ฌ์คํธ์ ๋ค์ํ ๊ธฐ๋ฅ์ ๊ฐ์กฐํ ์ ์์ต๋๋ค:
- C/C++ : ๋ฌ์คํธ๋ โ๋น๋ฆผโ๊ฒ์ฌ๋ฅผ ํตํด ์ ์ฒด ํด๋์ค์ ๋ฐํ์ ์๋ฌ๋ฅผ ์ ๊ฑฐํฉ๋๋ค. C/C++ ์ฒ๋ผ ์ฑ๋ฅ์ ํ๋ณด๋์ง๋ง ๋ฉ๋ชจ๋ฆฌ ์์ ์ฑ์ ๋ํ ๋ฌธ์ ๊ฐ ์์ต๋๋ค. ๋ํ, ํจํด๋งค์นญ์ด๋ ๋ด์ฅ ์ข ์์ฑ ๊ด๋ฆฌ ๊ฐ์ ํ๋์ธ์ด ๊ธฐ๋ฅ์ ๊ฐ์ง ์ ์์ต๋๋ค.
- Java, Go, Python, JaveScript : ํด๋น ์ธ์ด๋ค๊ณผ ๋์ผํ ๋ฉ๋ชจ๋ฆฌ ์์ ์ฑ๊ณผ โํ์ด๋ ๋ฒจโ์ธ์ด์ ๋๋์ ๋๋ ์ ์์ต๋๋ค. ๋ํ, GC๊ฐ ์๋ C/C++๊ณผ ๊ฐ์ด ๋น ๋ฅด๊ณ ์์ธก ๊ฐ๋ฅํ ์ฑ๋ฅ์ ์ป์ ์ ์๊ณ ํ์ํ ๊ฒฝ์ฐ ํ๋์จ์ด์ ๋ก์ฐ๋ ๋ฒจ๊น์ง ์ ๊ทผ ํ ์ ์์ต๋๋ค.
Make sure to ask the class which languages they have experience with. Depending on the answer you can highlight different features of Rust:
Experience with C or C++: Rust eliminates a whole class of runtime errors via the borrow checker. You get performance like in C and C++, but you donโt have the memory unsafety issues. In addition, you get a modern language with constructs like pattern matching and built-in dependency management.
Experience with Java, Go, Python, JavaSriptโฆ: You get the same memory safety as in those languages, plus a similar high-level language feeling. In addition you get fast and predictable performance like C and C++ (no garbage collector) as well as access to low-level hardware (should you need it)
Compile Time Guarantees
์ปดํ์ผ ์ ์ ์ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ:
- ์ด๊ธฐํ๋์ง ์๋ ๋ณ์๊ฐ ์์ต๋๋ค.
- ๋ฉ๋ชจ๋ฆฌ ๋์ ์์(๊ฑฐ์. ๊ฐ์์ฐธ์กฐ๋ ธํธ ์ฐธ๊ณ .)
- ๋ฉ๋ชจ๋ฆฌ ์ด์ค ํด์ ๋ ์๋ฉ๋๋ค.
- ๋ฉ๋ชจ๋ฆฌ ํด์ ํ ์ฌ์ฉ ์๋ฉ๋๋ค.
NULL
ํฌ์ธํฐ๋ ์์ต๋๋ค.- ์ ๊ธด ๋ฎคํ ์ค๋ฅผ ์์ ์ ์์ต๋๋ค.
- ์ค๋ ๋๊ฐ ๋ฐ์ดํฐ๋ ์ด์ค๊ฐ ์์ต๋๋ค.
- ์ดํฐ๋ ์ดํฐ(๋ฐ๋ณต์, iterator) ๋ฌดํจํ๊ฐ ์์ต๋๋ค.
Static memory management at compile time:
- No uninitialized variables.
- No memory leaks (mostly, see notes).
- No double-frees.
- No use-after-free.
- No
NULL
pointers.- No forgotten locked mutexes.
- No data races between threads.
- No iterator invalidation.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์์ ํ ๋ฌ์คํธ์์๋ ๋ฉ๋ชจ๋ฆฌ ๋์๊ฐ ๋ฐ์ํ๋ ๋ช๊ฐ์ง ์๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
Box::leak
์ ์ฌ์ฉํ์ฌ ๋ฐํ์ ์ด๊ธฐํ ๋ฐ ๋ฐํ์ ํฌ๊ธฐ ์ ์ ๋ณ์๋ฅผ ๊ฐ์ ธ์ฌ ์ ์์ต๋๋ค. ์ด๋ฅผ ํตํด ํฌ์ธํฐ ๋์๋ฅผ ๋ฐ์์ํฌ ์ ์์ต๋๋ค.std::mem::forget
์ ์ฌ์ฉํ์ฌ ์ปดํ์ผ๋ฌ๊ฐ ๊ฐ์ ๋ํด โ์๋๋กโ ๋ง๋ค ์ ์์ต๋๋ค(์๋ฉธ์๊ฐ ์คํ๋์ง ์์์ ์๋ฏธํฉ๋๋ค).Rc
๋๋Arc
๋ฅผ ์ฌ์ฉํ์ฌ ์ค์๋ก reference cycle์ ์์ฑํ ์๋ ์์ต๋๋ค.
๋ณธ ์ฝ์ค์์๋ โ๋ฉ๋ชจ๋ฆฌ ๋์ถ ์์โ์ โ์ฐ๋ฐ์ ์ธ ๋ฉ๋ชจ๋ฆฌ ๋์ถ ์์โ์ผ๋ก ์ดํดํด์ผ ํฉ๋๋ค.
It is possible to produce memory leaks in (safe) Rust. Some examples are:
- You can for use
Box::leak
to leak a pointer. A use of this could be to get runtime-initialized and runtime-sized static variables- You can use
std::mem::forget
to make the compiler โforgetโ about a value (meaning the destructor is never run).- You can also accidentally create a reference cycle with
Rc
orArc
.For the purpose of this course, โNo memory leaksโ should be understood as โPretty much no accidental memory leaksโ.
์ญ์์ฃผ
- mutexes : ๋ฉํฐ์ค๋ ๋ฉ์์ ์์์ ์ ์ ํ ์์
์๊ฐ ์ ๊ทธ๋ฉด(lock) ๋ค๋ฅธ ์์
์๋ค์ lock์ด ํด์ ๋ ๋๊น์ง ์์์ ๋ํด ์ ๊ทผ์ ํ ์ ์๋๋ก ๋ง๋ ๋ฐฉ์.
- cf. semaphore: ์์์ ์ ๊ทผ ํ ์ ์๋ ์์ ์(์ค๋ ๋,ํ๋ก์ธ์ค)์ ์๋ฅผ ๋ํ๋ด๋ ๊ฐ์ ๋ฌ์ ์ํธ ๋ฐฐ์ ํ๋ ๋ฐฉ์.
Runtime Guarantees
๋ฐํ์ ์ ์ ์๋์ง ์์(undefined) ๋์ ์์:
- ๋ฐฐ์ด ์ ๊ทผ์ ๊ฒฝ๊ณ ์ฒดํฌ
- ์ ์ํ์ ์ค๋ฒํ๋ก์ฐ๊ฐ ์ ์๋์ด์์ต๋๋ค.
No undefined behavior at runtime:
- Array access is bounds checked.
- Integer overflow is defined.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
ํคํฌ์ธํธ:
- ์ ์ํ ์ค๋ฒํ๋ก์ฐ๋ ์ปดํ์ผ ํ์ ํ๋ ๊ทธ๋ฅผ ํตํด ์ ์๋ฉ๋๋ค. ์ต์
์ ํจ๋(ํ๋ก๊ทธ๋จ ํฌ๋ ์) ํน์ wrap-around semantics์
๋๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก ๋๋ฒ๊ทธ ๋ชจ๋(
cargo build
)์์๋ ํจ๋์ด, ๋ฆด๋ฆฌ์ฆ ๋ชจ๋(cargo build --release
)์์๋ wrap-around์ด ๋ฐ์ํฉ๋๋ค. - ์ปดํ์ผ ํ๋ ๊ทธ๋ฅผ ์ฌ์ฉํ์ฌ ๊ฒฝ๊ณ์ฒดํฌ๋ฅผ ๋ฌด๋ ฅํ ํ ์ ์์ต๋๋ค.
unsafe
๋ฅผ ์ฌ์ฉํ๋๋ผ๋ ๋ง์ฐฌ๊ฐ์ง์ ๋๋ค. ํ์ง๋งunsafe
์์ ํธ์ถ ๊ฐ๋ฅํslice::get_unchecked
๊ฐ์ ํจ์๋ ๊ฒฝ๊ณ ๊ฒ์ฌ๋ฅผ ์ํํ์ง ์์ต๋๋ค.
Key points:
Integer overflow is defined via a compile-time flag. The options are either a panic (a controlled crash of the program) or wrap-around semantics. By default, you get panics in debug mode (
cargo build
) and wrap-around in release mode (cargo build --release
).Bounds checking cannot be disabled with a compiler flag. It can also not be disabled directly with the
unsafe
keyword. However,unsafe
allows you to call functions such asslice::get_unchecked
which does not do bounds checking.
Modern Features
๋ฌ์คํธ๋ ์ง๋ 40๋ ๊ฐ์ ๋ชจ๋ (ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๋ค์) ๊ฒฝํ์ผ๋ก ๋ง๋ค์ด์ก์ต๋๋ค.
Rust is built with all the experience gained in the last 40 years.
Language Features
- ์ด๊ฑฐํ๊ณผ ํจํด ๋งค์นญ
- ์ ๋๋ฆญ
- FFI1 ๋ฐํ์ ์ค๋ฒํค๋ ์์
- Enums and pattern matching.
- Generics.
- No overhead FFI.
Tooling
- ์์ฒญ๋ ์ปดํ์ผ๋ฌ ์๋ฌ ์ฒด์ปค
- ๋ด์ฅ ์ข ์์ฑ ๊ด๋ฆฌ์
- ๋ด์ฅ ํ ์คํธ ์ง์ ํด
- Great compiler errors.
- Built-in dependency manager.
- Built-in support for testing.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
ํคํฌ์ธํธ:
-
์ค๋ฅ๋ฅผ ์ฝ์ด๋ณด์๊ธฐ ๋ฐ๋๋๋ค โ ์ค๋๊ธฐ๊ฐ ๋ง์ ๊ฐ๋ฐ์๋ค์ด ์ปดํ์ผ๋ฌ ์ถ๋ ฅ์ ๋ฌด์ํ๋๋ฐ ์ต์ํด์ ธ ์์ต๋๋ค. ๋ฌ์คํธ ์ปดํ์ผ๋ฌ๋ ๋ค๋ฅธ ์ปดํ์ผ๋ฌ๋ณด๋ค ๋ ์๋ค์ค๋ฝ๊ณ , ๋ณต์ฌ-๋ถ์ฌ๋ฃ๊ธฐ ํ ์ ์๋ ์ ๋์ ์ฝ๋ ํผ๋๋ฐฑ์ ์ ๊ณตํ๋ ๊ฒฝ์ฐ๊ฐ ๋ง์ต๋๋ค.
-
๋ฌ์คํธ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ Java, Python์ด๋ Go์ ๊ฐ์ ์ธ์ด์ ๋นํด์๋ ๊ท๋ชจ๊ฐ ์์ต๋๋ค. ํ์ค์ด๋ ๊ธฐ๋ณธ์ ์ด๋ผ๊ณ ์๊ฐ๋๋ ์๋์ ๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ํฌํจ๋์์ง ์์ต๋๋ค:
- ๋์ ์์ฑ๊ธฐ, ํ์ง๋ง rand๋ฌธ์๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
- SSL ๋๋ TLS์ง์, ํ์ง๋ง rusttls๋ฌธ์๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
- JSON ์ง์, ํ์ง๋ง serde_json ๋ฌธ์๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
์ด๋ฌํ ๋ฐฐ๊ฒฝ์๋ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๊ธฐ๋ฅ์ ์ฌ๋ผ์ง ์ ์์ด์ ๋งค์ฐ ์์ ์ ์ด์ด์ผ ํ๊ธฐ ๋๋ฌธ์ ๋๋ค. ์์ ์์๋ค์์ ๋ฌ์คํธ ์ปค๋ฎค๋ํฐ๋ ๊ฐ์ฅ ์ข์ ๋ฐฉ๋ฒ์ ์ฌ์ ํ ์ฐพ๊ณ ์๊ณ ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ์ฌ๊ธฐ์ ๋ํ โ์ต์์ ์๋ฃจ์ โ์ด ์์ง ์์ต๋๋ค.
๋ฌ์คํธ๋ ์นด๊ณ ๋ผ๋ ํจํค์ง ๊ด๋ฆฌ์๊ฐ ๋ด์ฅ๋์ด ์๊ณ , ์๋ํํฐ ํฌ๋ ์ดํธ๋ฅผ ๋ค์ด๋ก๋, ์ปดํ์ผ ํ๊ธฐ ๋งค์ฐ ์ฝ์ต๋๋ค. ์ด ๋ํ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ์์ ์ด์ ๊ฐ ๋ ์ ์์ต๋๋ค.
์ข์ ์๋ํํฐ ํฌ๋ ์ดํธ๋ฅผ ์ฐพ๋ ๊ฒ ์์ฒด๊ฐ ๋ฌธ์ ๊ฐ ๋ ์ ์์ต๋๋ค. https://lib.rs ์ ๊ฐ์ ์ฌ์ดํธ๊ฐ ์ ๋ขฐํ ์ ์๋ ์ข์ ํฌ๋ ์ดํธ๋ฅผ ๋น๊ตํ์ฌ ์ฐพ๋๋ฐ ๋์์ ์ค ์ ์์ต๋๋ค.
Key points:
Remind people to read the errors โ many developers have gotten used to ignore lengthly compiler output. The Rust compiler is significantly more talkative than other compilers. It will often provide you with actionable feedback, ready to copy-paste into your code.
The Rust standard library is small compared to languages like Java, Python, and Go. Rust does not come with several things you might consider standard and essential:
- a random number generator, but see rand.
- support for SSL or TLS, but see rusttls.
- support for JSON, but see serde_json. The reasoning behind this is that functionality in the standard library cannot go away, so it has to be very stable. For the examples above, the Rust community is still working on finding the best solution โ and perhaps there isnโt a single โbest solutionโ for some of these things.
Rust comes with a built-in package manager in the form of Cargo and this makes it trivial to download and compile third-party crates. A consequence of this is that the standard library can be smaller.
Discovering good third-party crates can be a problem. Sites like https://lib.rs/ help with this by letting you compare health metrics for crates to find a good and trusted one.
์ญ์ฃผ
Foreign Function Interface. ํ ์ธ์ด ์ฝ๋๋ฅผ ํธ์ถํ๊ธฐ ์ํ ์ธํฐํ์ด์ค
Basic Syntax
๋๋ถ๋ถ์ ๋ฌ์คํธ ๋ฌธ๋ฒ์ C/C++๊ณผ ์ ์ฌํฉ๋๋ค.
- ๋ธ๋ก๊ณผ ์ค์ฝํ ๋ฒ์๋ ์ค๊ดํธ
{}
๋ก ํํํฉ๋๋ค. - ์ธ๋ผ์ธ ์ฃผ์์
// ...
, ๋ธ๋ก ์ฃผ์์/* ... */
๋ก ์ฌ์ฉํฉ๋๋ค. if
๋while
๊ฐ์ ํค์๋๋ ๋์ผํฉ๋๋ค.- ๋ณ์ ํ ๋น์
=
, ๋น๊ต๋==
๋ฅผ ์ฌ์ฉํฉ๋๋ค.
Much of the Rust syntax will be familiar to you from C or C++:
- Blocks and scopes are delimited by curly braces.
- Line comments are started with
//
, block comments are delimited by/* ... */
.- Keywords like
if
andwhile
work the same.- Variable assignment is done with
=
, comparison is done with==
.
Scalar Types
ํ์ Types | ์์ Literals | |
---|---|---|
๋ถํธ์๋ ์ ์ Signed integers | i8 , i16 , i32 , i64 , i128 , isize | -10 , 0 , 1_000 , 123i64 |
๋ถํธ์๋๋ ์ ์ Unsigned integers | u8 , u16 , u32 , u64 , u128 , usize | 0 , 123 , 10u16 |
๋ถ๋์์ Floating point numbers | f32 , f64 | 3.14 , -10.0e20 , 2f32 |
๋ฌธ์์ด Strings | &str | "foo" , r#"\\"# |
์ ๋์ฝ๋ ๋ฌธ์ Unicode scalar values | char | 'a' , 'ฮฑ' , 'โ' |
๋ฐ์ดํธ ๋ฌธ์ Byte strings | &[u8] | b"abc" , br#" " "# |
๋ถ๋ฆฌ์ธ Booleans | bool | true , false |
๊ฐ ํ์ ์ ํฌ๊ธฐ๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
- ์ ์ ๋ฐ ์์ํ์ ๋ค์ ์ซ์์ ๊ฐ์ bits ์
๋๋ค.(
i8
=8 bit) isize
์usize
๋ ํฌ์ธํฐ์ ๊ฐ์ ํฌ๊ธฐ์ ๋๋ค.1- ๋ฌธ์๋ 32 bit ์ ๋๋ค.
bool
์ 8 bit ์ ๋๋ค.
The types have widths as follows:
iN
,uN
, andfN
are N bits wide,isize
andusize
are the width of a pointer,char
is 32 bit wide,bool
is 8 bit wide.
์ญ์ฃผ
32๋นํธ ์์คํ ์์๋ 32๋นํธ, 64๋นํธ ์์คํ ์์๋ 64๋นํธ. C์ int์ ๊ฐ์.
Compound Types
ํ์ Types | ์์ Literals | |
---|---|---|
๋ฐฐ์ด Arrays | [T; N] | [20, 30, 40] , [0; 3] |
ํํ Tuples | () , (T,) , (T1, T2) , โฆ | () , ('x',) , ('x', 1.2) , โฆ |
๋ฐฐ์ด ์ ์ธ๊ณผ ์ ๊ทผ: |
Array assignment and access:
fn main() { let mut a: [i8; 10] = [42; 10]; //ํ์ ๊ณผ ์ฌ์ด์ฆ ์ ์ธ a[5] = 0; println!("a: {:?}", a); }
ํํ ์ ์ธ๊ณผ ์ ๊ทผ:
Tuple assignment and access:
fn main() { let t: (i8, bool) = (7, true); println!("1st index: {}", t.0); println!("2nd index: {}", t.1); }
์ญ์ฃผ
- js๊ธฐ์ค์ผ๋ก ์ค๋ช
ํ๋ฉด ํํ์ โ์์๊ฐ ์ค์ํด์ ์ฌ์ด์ฆ N์ผ๋ก ๊ณ ์ ๋ ๋ถ๋ณ(immutable) ๋ฐฐ์ดโ ์ด๋ผ๊ณ ๋ณด๋ฉด ๋จ.
- ์ ํํ๋ ์์(์์๊ฐ ์๋ฏธ๊ฐ ์๋ ๋ด์ฉ)์ ๋ฌถ์(๋ชจ์). ๊ฐฏ์N๊ฐ์ ๋ํด์ N-tuple์ด๋ผ๊ณ ๋ถ๋ฅด๋ฉฐ 2-tuple์ ํํ ์ฐ๊ธด ํจ.(cf. ์ด๊ฑฐํ)
References
C++๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก ๋ฌ์คํธ๋ ์ฐธ์กฐํ์ ๊ฐ์ต๋๋ค:
Like C++, Rust has references:
fn main() { let mut x: i32 = 10; let ref_x: &mut i32 = &mut x; *ref_x = 20; println!("x: {x}"); }
C++๊ณผ์ ์ฐจ์ด์ :
- Cํฌ์ธํฐ์ ์ ์ฌํ๊ฒ
ref_x
์ ํ ๋นํ ๊ฒฝ์ฐ ์ฐธ์กฐ๋ฅผ ํด์ ํด์ผ ํฉ๋๋ค. - ๋ฌ์คํธ๋ ํน์ ํ ๊ฒฝ์ฐ(๋ฉ์๋ ํธ์ถ)์ ์๋์ผ๋ก ์ฐธ์กฐ ํด์ ๋ฅผ ํฉ๋๋ค.
mut
๋ก ์ ์ธ๋ ์ฐธ์กฐ๋ ์๋ช ์ ๋ฐ๋ผ ๋ค๋ฅธ ๊ฐ์ผ๋ก ํ ๋น๋ ์ ์์ต๋๋ค.
Some differences from C++:
- We must dereference
ref_x
when assigning to it, similar to C pointers,- Rust will auto-dereference in some cases, in particular when invoking methods (try
count_ones
).- References that are declared as
mut
can be bound to different values over their lifetime.
์ญ์ฃผ
- count_ones ๋ฉ์๋๋ฅผ ๋ง๋ค์ด์ ํ ์คํธํด๋ณด์ธ์
Dangling References
๋ฌ์คํธ๋ ๋๊ธ๋ง ์ฐธ์กฐ๋ฅผ ๊ธ์งํฉ๋๋ค:
Rust will statically forbid dangling references:
fn main() { let ref_x: &i32; { let x: i32 = 10; ref_x = &x; } // ์ค์ฝํ๊ฐ ๋๋์ x๋ ์ญ์ ๋๊ณ ref_x๋ ์ฐธ์กฐ ํด์ ๋ฉ๋๋ค.(๋๊ธ๋ง ์ฐธ์กฐ) println!("ref_x: {ref_x}"); }
- ์ฐธ์กฐํ ๊ฐ(์ฐธ์กฐ)๋ ๋ณ์๋ก๋ถํฐ ๊ฐ์ โ๋น๋ฆฌ๋ ๊ฒโ์ ๋งํฉ๋๋ค.
- ๋ฌ์คํธ๋ ๋ชจ๋ ์ฐธ์กฐ์ ์๋ช ์ ์ถ์ ํ์ฌ ์ฐธ์กฐ๊ฐ ์ถฉ๋ถํ ์ค๋ ์ด์์์(์ฐธ์กฐ๊ฐ ์ฌ์ฉ๋ ๋๊น์ง)์ ๋ณด์ฅํฉ๋๋ค.
- ์์ ๊ถ ๋ถ๋ถ์์ โ๋น๋ฆผโ์ ๋ํด ์ข ๋ ๋ง์ ๊ฒ์ ๋ค๋ฃน๋๋ค.
- A reference is said to โborrowโ the value it refers to.
- Rust is tracking the lifetimes of all references to ensure they live long enough.
- We will talk more about borrowing when we get to ownership.
์ญ์ฃผ
- ๋๊ธ๋ง ์ฐธ์กฐ: ์ฐธ์กฐ ํฌ์ธํฐ๊ฐ ๋์ด์ ์ ํจํ์ง ์์ ๊ฐ์ ๊ฐ๋ฅดํค๊ฒ ๋๋ ๊ฒฝ์ฐ
Slices
์ฌ๋ผ์ด์ค๋ฅผ ์ฌ์ฉํ๋ฉด ํฐ ์ปฌ๋ ์ ์ ๋ถ๋ถ๋ง ํ์ธํ ์ ์์ต๋๋ค.
A slice gives you a view into a larger collection:
fn main() { let a: [i32; 6] = [10, 20, 30, 40, 50, 60]; println!("a: {a:?}"); let s: &[i32] = &a[2..4]; println!("s: {s:?}"); }
- ์ฌ๋ผ์ด์ค๋ ์ฌ๋ผ์ด์ค ํ์ ์ผ๋ก๋ถํฐ ๋ฐ์ดํฐ๋ฅผ โ๋น๋ คโ์ต๋๋ค.
- ์ง๋ฌธ:
a[3]
์ผ๋ก ์์ ํ๋ฉด ๋ฌด์จ ์ผ์ด ์์ด๋ ๊น์? - Slices borrow data from the sliced type.
- Question: What happens if you modify
a[3]
?
String
vs str
์ด์ ๋ฌ์คํธ์ ๋๊ฐ์ง ๋ฌธ์์ด ํ์ ์ ๋ํด์ ์ดํดํด ๋ณด๊ฒ ์ต๋๋ค.:
We can now understand the two string types in Rust:
fn main() { let s1: &str = "Hello"; println!("s1: {s1}"); let mut s2: String = String::from("Hello "); println!("s2: {s2}"); s2.push_str(s1); println!("s2: {s2}"); }
๋ฌ์คํธ ์ฉ์ด:
&str
ํ์ ์ ๋ฌธ์์ด ์ฌ๋ผ์ด์ค์ ๋ถ๋ณ์ฐธ์กฐ์ ๋๋ค.String
ํ์ ์ ๊ฐ๋ณ ๋ฌธ์์ด ๋ฒํผ์ ๋๋ค.
Rust terminology:
&str
an immutable reference to a string slice.String
a mutable string buffer.
์ญ์ฃผ
- str์ ๋ฌธ์ ๋ฆฌํฐ๋ด, &์ ์ฐธ์กฐ ํ์ ์ ๋๋ค.
Functions
๋ฌ์คํธ ๋ฒ์ ์ FizzBuzz ํจ์์ ๋๋ค:
A Rust version of the famous FizzBuzz interview question:
fn main() { // ํ๋จ์ ์. ๊ตณ์ด ์๋จ์ ๋ณ๋ ์ ์ธํ ํ์ ์์. // Defined below, no forward declaration needed fizzbuzz_to(20); } fn is_divisible_by(lhs: u32, rhs: u32) -> bool { if rhs == 0 { // ์ฝ๋ ์ผ์ด์ค. // Corner case, early return return false; } // ๋ง์ง๋ง ํํ์์ ๋ฐํ๊ฐ์ ๋ํ๋ ๋๋ค. // The last expression is the return value lhs % rhs == 0 } // `()` ๋ฐํ๊ฐ์ ๋ฐํํ ๊ฐ์ด ์์์ ๋ํ๋ ๋๋ค. // No return value means returning the unit type `()` fn fizzbuzz(n: u32) -> () { match (is_divisible_by(n, 3), is_divisible_by(n, 5)) { (true, true) => println!("fizzbuzz"), (true, false) => println!("fizz"), (false, true) => println!("buzz"), (false, false) => println!("{n}"), } } //๋ฐํ๊ฐ์ด ์๋ ๊ฒฝ์ฐ(`-> ()`) ์๋ต ๊ฐ๋ฅํฉ๋๋ค. // `-> ()` is normally omitted fn fizzbuzz_to(n: u32) { for n in 1..=n { fizzbuzz(n); } }
์ญ์ฃผ
- corner case: ๋ณตํฉ ๊ฒฝ๊ณ ์กฐ๊ฑด. ๋ณ์์ ํ๊ฒฝ์ ์ธ ์์๋ก ์ธํด์ ๋ก์ง์ ๋ฌธ์ ๊ฐ ์๋ ๊ฒฝ์ฐ. ex. ๋๋๊ธฐ ๋ก์ง์์ 0์ผ๋ก ๋๋๋ ๊ฒฝ์ฐ.
- edge case: ๊ฒฝ๊ณ์กฐ๊ฑด. ๋งค๊ฐ๋ณ์ ๊ฐ์ด ๊ทน๋จ์ ์ธ ์ต๋/์ต์๊ฐ(๋ก์ง ์ ํจ๋ฒ์ ๋) ์ด์์ธ ๊ฒฝ์ฐ.
- fizzbuzz: ์ซ์๋ฅผ ์ ๋ ฅ๋ฐ์์ n์ผ๋ก ๋๋๋ฉด fizz, m์ผ๋ก ๋๋๋ฉด buss, ๋๋ค ๋๋๋ฉด fizzbuzz, ์๋๋๋ฉด ์ ๋ ฅ๊ฐ์ ์ถ๋ ฅํ๋ ํ ์คํธ๋ก ์์ฃผ ์ฐ๋ ๋ฌธ์ ์ ๋๋ค. ์์ ์ n,m์ 3,5
Methods
๋ฌ์คํธ๋ ๋ฉ์๋(ํน์ ํ์ ๊ณผ ๊ด๊ณ๋ ๊ฐ๋จํ ํจ์)๋ฅผ ๊ฐ์ง๋๋ค. ๋ฉ์๋์ ์ฒซ๋ฒ์งธ ์ธ์๋ ํธ์ถ๋ถ ํ์ ์ ์ธ์คํด์ค ์ ๋๋ค.(self, this)
Rust has methods, they are simply functions that are associated with a particular type. The first argument of a method is an instance of the type it is associated with:
// ๊ตฌ์กฐ์ฒด ์ ์ธ์ ๋๋ค. struct Rectangle { width: u32, height: u32, } // ๊ตฌ์กฐ์ฒด์ ๊ตฌํ๋ ๋ฉ์๋ ๋ค์ ๋๋ค. // ๊ตฌ์กฐ์ฒด ์์ฒด์๋ ๋ฐ์ดํฐ๋ง ์ ์ธ์ด ๋์ด impl ํค์๋๋ก ํด๋น ๊ตฌ์กฐ์ฒด์ ๋ฉ์๋๋ฅผ ์ ์ธ/์ฐ๊ฒฐ ํด์ฃผ๋ ๋ฌธ๋ฒ ๊ตฌ์กฐ์ ๋๋ค. // ์ฒซ๋ฒ์งธ ์ธ์๋ ํด๋น ๊ตฌ์กฐ์ฒด ์์ (self)์ ๋๋ค. impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn inc_width(&mut self, delta: u32) { self.width += delta; } } fn main() { let mut rect = Rectangle { width: 10, height: 5 }; // ๋ฉ์๋๋ .์ผ๋ก ํธ์ถํ๋ฉฐ area์ self.width๋ 10, self.height๋ 5์ ๋๋ค. println!("old area: {}", rect.area()); rect.inc_width(5); println!("new area: {}", rect.area()); }
- ์ค๋๊ณผ ๋ด์ผ ๊ฐ์์์ ๋ ๋ง์ ๋ฉ์๋ ์ฌ์ฉ๋ฒ์ ๋ค๋ฃฐ ๊ฒ์ ๋๋ค.
- We will look much more at methods in todayโs exercise and in tomorrowโs class.
Function Overloading
์ค๋ฒ๋ก๋ฉ์ ์ง์๋์ง ์์ต๋๋ค:
- ๊ฐ๋ณํจ์๋ ๋จ์ผ ๊ตฌํ๋ง ๊ฐ์ต๋๋ค.
- ํญ์ ๊ณ ์ ๋ ์์ ๋งค๊ฐ๋ณ์๋ง ๊ฐ์ต๋๋ค.
- ํญ์ ๊ณ ์ ๋ ๋จ์ผ ํ์ ์งํฉ์ ์ฌ์ฉํฉ๋๋ค.
- ๋งค๊ฐ๋ณ์์ ๊ธฐ๋ณธ ๊ฐ์ ์ง์๋์ง ์์ต๋๋ค.
- ๋ชจ๋ ํธ์ถ๋ถ์์๋ ๋์ผํ ์์ ์ธ์๋ฅผ ์ค์ ํด์ผํฉ๋๋ค.
- ๋์์ผ๋ก ๋งคํฌ๋ก๋ฅผ ์ฌ์ฉํ๊ธฐ๋ ํฉ๋๋ค.
ํ์ง๋ง, ํจ์์ ๋งค๊ฐ๋ณ์๋ ์ ๋๋ฆญ์ ์ ์ฉํ ์ ์์ต๋๋ค.
Overloading is not supported:
- Each function has a single implementation:
- Always takes a fixed number of parameters.
- Always takes a single set of parameter types.
- Default values are not supported:
- All call sites have the same number of arguments.
- Macros are sometimes used as an alternative.
However, function parameters can be generic:
// ์ ๋๋ฆญ fn pick_one<T>(a: T, b: T) -> T { if std::process::id() % 2 == 0 { a } else { b } } fn main() { println!("coin toss: {}", pick_one("heads", "tails")); println!("cash prize: {}", pick_one(500, 1000)); }
์ญ์ฃผ
- std::process::id: OS๊ด๋ จ ํ๋ก์ธ์ค ID๋ฅผ ๋ฐํํ๋ ํจ์์ ๋๋ค.
- for js developer:
::
ํํ์ ์ฝ๊ฒ ๋งํด static ํจ์ ํธ์ถ์ ๋๋ค.
Day 1: Morning Exercises
์ด๋ฒ ์ฐ์ต๋ฌธ์ ๋ ๋ฌ์คํธ์ ๋ ๋ถ๋ถ์ ์์๋ณผ ๊ฒ์ ๋๋ค:
- ํ์ ์ ์๋ฌต์ ๋ณํ
- ๋ฐฐ์ด๊ณผ
for
loops
In these exercises, we will explore two parts of Rust:
Implicit conversions between types.
Arrays and
for
loops.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์ฐ์ต๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋๋ฐ ๊ณ ๋ คํด์ผ ํ ์ฌํญ๋ค:
- ๊ฐ๋ฅํ ๊ฒฝ์ฐ ๋ก์ปฌํ๊ฒฝ์์ ์งํํ๋ฉด ํ ์คํธ ์๋ํฐ์ ๋์์ ๋ฐ์ ์ ์์ต๋๋ค. [์นด๊ณ ์ฌ์ฉํ๊ธฐ:Using Cargo] ์ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
- ํน์ ๋ฌ์คํธ ํ๋ ์ด๊ทธ๋ผ์ด๋๋ฅผ ์ด์ฉํ ์ ์์ต๋๋ค.
ํ์ด์ง ๋ฐ์ผ๋ก ์ด๋ํ ๊ฒฝ์ฐ ์์ฑํ ๋ด์ฉ์ด ์์ค๋๊ธฐ ๋๋ฌธ์ ์ ๊ณต๋๋ ์ฝ๋ ์ค๋ํซ์ ์๋์ ์ผ๋ก ํธ์งํ ์ ์์ต๋๋ค.
A few things to consider while solving the exercises:
Use a local Rust installation, if possible. This way you can get auto-completion in your editor. See the page about Using Cargo for details on installing Rust.
Alternatively, use the Rust Playground.
The code snippets are not editable on purpose: the inline code snippets lose their state if you navigate away from the page.
Implicit Conversions
๋ฌ์คํธ๋ C++๊ณผ ๋ค๋ฅด๊ฒ ํ์ ๊ฐ _์๋ฌต์ ๋ณํ_์ ์๋์ผ๋ก ์ ์ฉํ์ง ์์ต๋๋ค. ์๋ ์์๋ฅผ ํ์ธํด ๋ณด์ธ์:
Rust will not automatically apply implicit conversions between types (unlike C++). You can see this in a program like this:
fn multiply(x: i16, y: i16) -> i16 { x * y } fn main() { let x: i8 = 15; let y: i16 = 1000; println!("{x} * {y} = {}", multiply(x, y)); }
๋ฌ์คํธ์ ์ ์ํ ํ์
์ ๋ชจ๋ From<T>
์ Into<T>
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ์ฌ ๋ ์ฌ์ด๋ฅผ ๋ณํ ํ ์ ์์ต๋๋ค.
From<T>
ํธ๋ ์ดํธ๋ ๋จ์ผ from()
๋ฉ์๋๋ฅผ ๊ฐ์ง๊ณ ์๊ณ , Into<T>
ํธ๋ ์ดํธ๋ ๋จ์ผ into()
๋ฉ์๋๋ฅผ ๊ฐ์ง๊ณ ์์ต๋๋ค.
์ด๋ฌํ ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ๋ ๊ฒ์ ํ์
์ด ๋ค๋ฅธ ํ์
์ผ๋ก ๋ณํํ๋ ๊ฒ์ ํํํ๋ ๋ฐฉ๋ฒ์
๋๋ค.
The Rust integer types all implement the
From<T>
andInto<T>
traits to let us convert between them. TheFrom<T>
trait has a singlefrom()
method and similarly, theInto<T>
trait has a singleinto()
method. Implementing these traits is how a type expresses that it can be converted into another type.
ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์๋ From<i8> for i16
๊ฐ ๊ตฌํ๋์ด ์๋๋ฐ ์ด๊ฒ์ ์ฐ๋ฆฌ๊ฐ i8
ํ์
์ ๋ณ์ x
๋ฅผ i16::from(x)
๋ฅผ ํธ์ถํ์ฌ i16
ํ์
์ผ๋ก ๋ณํํ ์ ์๋ค๋ ์๋ฏธ์
๋๋ค.
(ํน์ ๋ ๊ฐ๋จํ๊ฒ x.into()
๋ฅผ ์ฌ์ฉํฉ๋๋ค.)
From<i8> for i16
์ ๊ตฌํ์ ์๋์ผ๋ก Into<i16> for i8
๋ฅผ ์์ฑํ๊ธฐ ๋๋ฌธ์
๋๋ค.
The standard library has an implementation of
From<i8> for i16
, which means that we can convert a variablex
of typei8
to ani16
by callingi16::from(x)
. Or, simpler, withx.into()
, becauseFrom<i8> for i16
implementation automatically create an implementation ofInto<i16> for i8
.
- ์ ์์ ์ฝ๋๋ฅผ ์คํํด์ ๋ฐ์ํ ์ค๋ฅ๋ฅผ ํ์ธํด ๋ณด์ธ์
into()
๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ์ฝ๋๋ฅผ ์์ ํ์ธ์x
์y
๋ฅผ `f32โ์ด๋ โboolโ, โi128โ ๋ฑ์ผ๋ก ๋ฐ๊ฟ์ ํด๋น ํ์ ๋ค๋ก ๋ณํ์ด ๋๋์ง ํ์ธํด๋ณด์ธ์
- ์์ ์ฌ์ด์ฆ ํ์ ์์ ํฐ ์ฌ์ด์ฆ๋ก ๋ณ๊ฒฝํด๋ณด์๊ณ ๊ทธ ๋ฐ๋๋ก๋ ํด๋ณด์ธ์
- ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ฌธ์์์ ์๋ํด ๋ณธ ์ผ์ด์ค๊ฐ ๊ตฌํ๋์ด ์๋์ง ํ์ธํด ๋ณด์ธ์.
- Execute the above program and look at the compiler error.
- Update the code above to use
into()
to do the conversion.- Change the types of
x
andy
to other things (such asf32
,bool
,i128
) to see which types you can convert to which other types. Try converting small types to big types and the other way around. Check the standard library documentation to see ifFrom<T>
is implemented for the pairs you check.
Arrays and for
Loops
์ฐ๋ฆฌ๋ ๋ฐฐ์ด์ ์๋์ ๊ฐ์ด ์ ์ธ ํ ์ ์์์ ๋ณด์์ต๋๋ค:
We saw that an array can be declared like this:
#![allow(unused)] fn main() { let array = [10, 20, 30]; }
๋ฐฐ์ด์ {:?}
ํํ๋ก ํ์ํ์ฌ ์ถ๋ ฅํ ์ ์์ต๋๋ค.
You can print such an array by asking for its debug representation with
{:?}
:
fn main() { let array = [10, 20, 30]; println!("array: {array:?}"); }
๋ฌ์คํธ์์๋ for
ํค์๋๋ฅผ ์ฌ์ฉํด ๋ฐฐ์ด์ด๋ ๋ฒ์๋ฅผ ๋ฐ๋ณตํ ์ ์์ต๋๋ค:
Rust lets you iterate over things like arrays and ranges using the
for
keyword:
fn main() { let array = [10, 20, 30]; print!("Iterating over array:"); for n in array { print!(" {n}"); } println!(); print!("Iterating over range:"); for i in 0..3 { print!(" {}", array[i]); } println!(); }
์์ ์์ ์์ ํ๋ ฌ์ ์์๊ฒ ์ถ๋ ฅํ๋ pretty_print
ํจ์์ ํ๋ ฌ์ ์ ์น(ํ๊ณผ ์ด์ ๋ณ๊ฒฝ)์ํค๋ transpose
ํจ์๋ฅผ ์์ฑํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค.
Use the above to write a function
pretty_print
which pretty-print a matrix and a functiontranspose
which will transpose a matrix (turn rows into columns):
๋ ํจ์ ๋ชจ๋ 3ร3 ํ๋ ฌ์์ ์๋ํ๋๋ก ํ๋ ์ฝ๋ฉํฉ๋๋ค.
Hard-code both functions to operate on 3 ร 3 matrices.
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํด์ ๊ตฌํํ์๋ฉด ๋ฉ๋๋ค.
Copy the code below to https://play.rust-lang.org/ and implement the functions:
// TODO: ๊ตฌํ์ด ์๋ฃ๋๋ฉด ์๋ ์ค์ ์ญ์ ํฉ๋๋ค. // TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] { unimplemented!() } fn pretty_print(matrix: &[[i32; 3]; 3]) { unimplemented!() } fn main() { let matrix = [ [101, 102, 103], // <-- the comment makes rustfmt add a newline [201, 202, 203], [301, 302, 303], ]; println!("matrix:"); pretty_print(&matrix); let transposed = transpose(matrix); println!("transposed:"); pretty_print(&transposed); }
Bonus Question
ํ๋์ฝ๋ฉ๋ 3ร3 ํ๋ ฌ ์
๋ ฅ์ &[i32]
์ฌ๋ผ์ด์ค๋ฅผ ํตํด ์ธ์์ ๋ฐํ๊ฐ์ ์ ์๊ฐ ๊ฐ๋ฅํ๊ฐ์?
์์ปจ๋ฐ &[&[i32]]
๋ 2์ฐจ์ ์ฌ๋ผ์ด์ค์ ์ฌ๋ผ์ด์ค ์
๋๋ค. ๊ฐ๋ฅํ๋ค๋ฉด/ํ์ง ์๋ค๋ฉด ์ ๊ทธ๋ฐ๊ฐ์?
Could you use
&[i32]
slices instead of hard-coded 3 ร 3 matrices for your argument and return types? Something like&[&[i32]]
for a two-dimensional slice-of-slices. Why or why not?
ํ๋ก๋์
ํ์ง์ ๊ตฌํ์ ๋ํด์๋ ndarray
ํฌ๋ ์ดํธ๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
See the
ndarray
crate for a production quality implementation.
์ญ์ฃผ
- C/C++๋ js์ ๋ํด์ ์ด๋์ ๋ ์ง์์ด ์๋๊ฑธ ์ ์ ๋ก ํ๊ธฐ๋๋ฌธ์ ์ฒซ ๋ฌธ์ ๋ถํฐ ๋์ด๋๊ฐ ์กฐ๊ธ ์์ง ์์๊น ์ถ์ต๋๋ค๋ง..
ํํธ
- for๋ฅผ ์ด์ฉํ ์ถ๋ ฅ๊ณผ for๋ฅผ ์ด์ฉํด [i][j] ๋ณํํ๋ ํจ์์ ๋๋ค.
Variables
๋ฌ์คํธ๋ ์ ์ ํ์ดํ์ ํตํด ํ์ ์ธ์ดํํฐ(ํ์ ์์ )์ ์ ๊ณตํฉ๋๋ค. ๋ณ์ ๋ฐ์ธ๋ฉ์ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ถ๋ณ(immutable)ํฉ๋๋ค.
Rust provides type safety via static typing. Variable bindings are immutable by default:
fn main() { let x: i32 = 10; println!("x: {x}"); // x = 20; // println!("x: {x}"); }
Type Inference
๋ฌ์คํธ๋ ๋ณ์๊ฐ ์ด๋ป๊ฒ ์ฌ์ฉ๋๋์ง ํ์ธํ์ฌ ํ์ ์ถ๋ก ์ ์ ๊ณตํฉ๋๋ค.
Rust will look at how the variable is used to determine the type:
fn takes_u32(x: u32) { println!("u32: {x}"); } fn takes_i8(y: i8) { println!("i8: {y}"); } fn main() { let x = 10; let y = 20; takes_u32(x); takes_i8(y); // takes_u32(y); }
Static and Constant Variables
์ ์ญ ์ํ(state) ์ ์ ๋ณ์์ ์์๋ก ๊ด๋ฆฌ๋ฉ๋๋ค.
Global state is managed with static and constant variables.
const
์ปดํ์ผ ์์ ์ ์์๋ฅผ ์ ์ธํ ์ ์์ต๋๋ค.
You can declare compile-time constants:
const DIGEST_SIZE: usize = 3; const ZERO: Option<u8> = Some(42); fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] { let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE]; for (idx, &b) in text.as_bytes().iter().enumerate() { digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b); } digest } fn main() { let digest = compute_digest("Hello"); println!("Digest: {digest:?}"); }
static
๋ง์ฐฌ๊ฐ์ง๋ก ์ ์ ๋ณ์๋ ์ ์ธํ ์ ์์ต๋๋ค.
You can also declare static variables:
static BANNER: &str = "Welcome to RustOS 3.14"; fn main() { println!("{BANNER}"); }
๊ฐ๋ณ ์ ์ ๋ฐ์ดํฐ์ ๋ํด์๋ ์์ ํ์ง ์์ ๋ฌ์คํธ ํํธ์์ ์ดํด๋ด ๋๋ค.
We will look at mutating static data in the chapter on Unsafe Rust.
Scopes and Shadowing
์ธ๋ถ ์ค์ฝํ์ ๋์ผ ์ค์ฝํ ๋ฒ์์ ๋ณ์๋ฅผ ๊ฐ๋ฆด ์ ์์ต๋๋ค.(๋ณ์ ์๋์)
You can shadow variables, both those from outer scopes and variables from the same scope:
fn main() { let a = 10; println!("before: {a}"); { let a = "hello"; println!("inner scope: {a}"); let a = true; println!("shadowed in inner scope: {a}"); } println!("after: {a}"); }
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
- ์๋์์ ๋ชจํธํด ๋ณด์ผ ์ ์์ง๋ง
.unwrap()
์ดํ์ ๊ฐ์ ํ ๋นํ๋๋ฐ ์ฉ์ดํฉ๋๋ค. - ์๋ ์ฝ๋๋ ์ปดํ์ผ๋ฌ๊ฐ ์คํฌํฌ์์ ๋ณ๊ฒฝ๋์ง ์๋ ๋ณ์๋ฅผ ์๋์ํ ๋ ํ์ ์ด ๋์ผํ๋๋ผ๋ ๋ฉ๋ชจ๋ฆฌ ์์น๋ฅผ ๋จ์ ์ฌ์ฌ์ฉ ํ ์ ์๋ ์ด์ ๋ฅผ ๋ณด์ฌ์ค๋๋ค.(์๋ณธ a๋ฅผ ์ฐธ์กฐํ b์ ์๋์ ๋ a(a+1) ๋๋ค ์ด์์์ด์ผ ํ๋ฏ๋ก ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ฐ๋ก ํ ๋นํฉ๋๋ค.)
- Shadowing looks obscure at first, but is convenient for holding on to values after
.unwrap()
.- The following code demonstrates why the compiler canโt simply reuse memory locations when shadowing an immutable variable in a scope, even if the type does not change.
fn main() { let a = 1; let b = &a; let a = a + 1; println!("{a} {b}"); }
์ญ์ฃผ
- after์ ๊ฒฝ์ฐ inner scope ์๋ช ์ด ๋คํด์ ์๋ ๋ณ์์ธ a๊ฐ ํ์๋๋ ๊ฒ๋๋ค.
Memory Management
์ ํต์ ์ผ๋ก, ํ๋ก๊ทธ๋๋ฐ ์ธ์ด๋ ํฌ๊ฒ ๋๊ฐ์ง๋ก ๋ถ๋ฅ ๋ฉ๋๋ค:
- ์์ค๋ ๋ฒจ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ(์๋ ์ ์ด): C, C++, Pascal, โฆ
- ๋ฐํ์ ์ ์๋ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ๋ฅผ ํตํ ์์ ์ฑ ์ ๊ณต1: Java, Python, Go, Haskell, โฆ
Traditionally, languages have fallen into two broad categories:
- Full control via manual memory management: C, C++, Pascal, โฆ
- Full safety via automatic memory management at runtime: Java, Python, Go, Haskell, โฆ
๋ฌ์คํธ๋ ์๋ก์ด ํํ๋ฅผ ์ ์ํฉ๋๋ค:
์ปดํ์ผ ์ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ๋ฅผ ํตํ ์์ ์ฑ๊ณผ ์ ์ด ์ ๊ณต
Rust offers a new mix:
Full control and safety via compile time enforcement of correct memory management.
์ด๊ฒ์ ๋ช ์์ ์ธ ์์ ๊ถ ์ปจ์ ์ ํตํด ์ด๋ค์ง๋๋ค.
์ฐ์ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ๊ฐ ์ด๋ค์ง๋ ๋ฐฉ์์ ๋ค์ ์ดํด ๋ณด๊ฒ ์ต๋๋ค.
It does this with an explicit ownership concept. First, letโs refresh how memory management works.
GC๊ฐ์๊ฑฐ
The Stack vs The Heap
-
์คํ: ์ง์ญ๋ณ์๋ฅผ ์ํ ๋ฉ๋ชจ๋ฆฌ ์ ์ฐ์์ ์ธ ์์ญ
- ๊ฐ์ ์ฌ์ ์ ์๋ ๊ณ ์ ํฌ๊ธฐ๋ฅผ ๊ฐ์ต๋๋ค.
- ๊ทน๋๋ก ๋น ๋ฆ: ๋จ์ง ์คํ ํฌ์ธํธ๋ง ์ด๋๋ฉ๋๋ค.
- ๊ด๋ฆฌ๊ฐ ์ฌ์: ํจ์ ํธ์ถ์ ๋ฐ๋ฆ ๋๋ค.
- ๋ฉ๋ชจ๋ฆฌ ์ธ์ ์ฑ
-
ํ: ํจ์ ํธ์ถ ์ธ๋ถ์ ๊ฐ์ด ์ ์ฅ๋๋ ๊ณณ
- ๊ฐ์ ๋ฐํ์ ์ ๊ฒฐ์ ๋๋ ๋์ ํฌ๊ธฐ๋ฅผ ๊ฐ์ต๋๋ค.
- ์คํ์ ๋นํด์๋ ์ฝ๊ฐ ๋๋ฆผ: ์ฝ๊ฐ์ ์ถ๊ฐ ๊ธฐ๋ก(๋ถ๊ธฐ)1์ด ํ์ํจ.
- ๋ฉ๋ชจ๋ฆฌ ์ธ์ ์ฑ์ ๋ณด์ฅํ์ง ์์.
Stack: Continuous area of memory for local variables.
- Values have fixed sizes known at compile time.
- Extremely fast: just move a stack pointer.
- Easy to manage: follows function calls.
- Great memory locality.
Heap: Storage of values outside of function calls.
- Values have dynamic sizes determined at runtime.
- Slightly slower than the stack: some book-keeping needed.
- No guarantee of memory locality.
์ญ์ฃผ
book-keeping(๋ถ๊ธฐ)๋ ํ๊ณ์ชฝ ์ฉ์ด์ด๊ณ ์ด๋ ํ ์ฌ๊ฑด์ ๋ํด ์์ฝ, ์ ๋ฆฌํด์ ๋ณ๋์ ์ฅ๋ถ์ ๊ธฐ๋กํ๋ ๊ฒ์ ๋๋ค. ์ฌ๊ธฐ์๋ ๋ฐ์ดํฐ๋ฅผ ํ์ ์ ์ฅํ๊ณ ํด๋น ํ ์ฃผ์๋ฅผ ์คํ์ ์ ์ฅํ๋ ํํ์ ๋ํ ์ค๋ช ์ ๋๋ค.
Stack Memory
String
ํ์
์ ํ์ ๋์ ์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ํฌ๊ธฐ ๊ณ ์ ๋ ๋ฐ์ดํฐ(ํ ๋ฐ์ดํฐ์ ๋ํ ์ ๋ณด)๋ฅผ ์คํ์ ์ ์ฅํฉ๋๋ค.
Creating a
String
puts fixed-sized data on the stack and dynamically sized data on the heap:
fn main() { let s1 = String::from("Hello"); }
Manual Memory Management
์ฌ์ฉ์๊ฐ ์ง์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ํ ๋น, ํด์ ํฉ๋๋ค.
You allocate and deallocate heap memory yourself.
C Example
malloc
๋ก ํ ๋นํ๋ ํฌ์ธํฐ๋ง๋ค free
๋ฅผ ํธ์ถํด์ผ ํฉ๋๋ค:
You must call
free
on every pointer you allocate withmalloc
:
void foo(size_t n) {
int* int_array = (int*)malloc(n * sizeof(int));
//
// ... lots of code
//
free(int_array);
}
๋ง์ฝmalloc
๊ณผ free
์ฌ์ด์์ ํจ์๊ฐ ๋จผ์ ๋ฐํ๋๋ฉด ๋ฉ๋ชจ๋ฆฌ ๋์๊ฐ ์ผ์ด๋ฉ๋๋ค.
: ํฌ์ธํฐ๊ฐ ์์ค๋์ด ๋ฉ๋ชจ๋ฆฌ ํ ๋น์ ํด์ ํ ์ ์๊ฒ ๋ฉ๋๋ค.
Memory is leaked if the function returns early between
malloc
andfree
: the pointer is lost and we cannot deallocate the memory.
Scope-Based Memory Management
์์ฑ์์ ์๋ฉธ์๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ฒด์ ์๋ช ์ ์ฐ๊ฒฐ(hook)ํ ์ ์์ต๋๋ค.
Constructors and destructors let you hook into the lifetime of an object.
ํฌ์ธํฐ๋ฅผ ๊ฐ์ฒด์ ๋ํํ์ฌ ๊ฐ์ฒด๊ฐ ์๋ฉธ๋ ๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ํด์ ํ ์ ์์ต๋๋ค. ์ปดํ์ผ๋ฌ๋ ์์ธ(exception)๊ฐ ๋ฐ์ํ๋๋ผ๋ ์ด๋ฅผ ๋ณด์ฅํฉ๋๋ค.
By wrapping a pointer in an object, you can free memory when the object is destroyed. The compiler guarantees that this happens, even if an exception is raised.
์ด๋ฅผ ์ข ์ข RAII(Resource Acquisition Is Initialization, ๋ฆฌ์์ค ํ๋์ ์ด๊ธฐํ๋ค)์ด๋ผ๊ณ ํ๋ฉฐ, RAIIํจํด์ ์ค๋งํธ ํฌ์ธํฐ๋ฅผ ์ ๊ณตํฉ๋๋ค.
This is often called resource acquisition is initialization (RAII) and gives you smart pointers.
C++ Example
void say_hello(std::unique_ptr<Person> person) {
std::cout << "Hello " << person->name << std::endl;
}
std::unique_ptr
๊ฐ์ฒด๋ ์คํ์ ํ ๋น๋๋ฉฐ, ํ์ ํ ๋น๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๊ฐ๋ฆฌํต๋๋ค(point).say_hello
ํจ์๊ฐ ๋๋๋ฉดstd::unique_ptr
์ ์๋ฉธ์๊ฐ ์คํ๋ฉ๋๋ค.- ์๋ฉธ์๋
Person
๊ฐ์ฒด๊ฐ ๊ฐ๋ฅดํค๋(point) ๊ณณ์ ํด์ ํฉ๋๋ค.
- The
std::unique_ptr
object is allocated on the stack, and points to memory allocated on the heap.- At the end of
say_hello
, thestd::unique_ptr
destructor will run.- The destructor frees the
Person
object it points to.
ํน๋ณํ ์ด๋ ์์ฑ์๋ ์์ ๊ถ์ ํจ์๋ก ์ ๋ฌํ ๋ ์ฌ์ฉ๋ฉ๋๋ค.
Special move constructors are used when passing ownership to a function:
std::unique_ptr<Person> person = find_person("Carla");
say_hello(std::move(person));
์ญ์ฃผ
- C++ ์ง์์ด ์งง์์ ๋ฒ์ญ์ด ๋ง๋ ๋ชจ๋ฅด๊ฒ ์.
Automatic Memory Management
์๋, ์ค์ฝํ๊ธฐ๋ฐ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ์ ๋์์ธ ์๋ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ ์ ๋๋ค:
- ๊ฐ๋ฐ์๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ช ์์ ์ผ๋ก ํ ๋น/ํด์ ํ์ง ์์ต๋๋ค.
- ๊ฐ๋น์ง ์ปฌ๋ ํฐ(GC)๋ ๊ฐ๋ฐ์ ๋์ ์ฌ์ฉ๋์ง ์๋ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ฐพ์ ํด์ ํฉ๋๋ค.
An alternative to manual and scope-based memory management is automatic memory management:
- The programmer never allocates or deallocates memory explicitly.
- A garbage collector finds unused memory and deallocates it for the programmer.
Java Example
person
๊ฐ์ฒด๋ sayHello
ํจ์ ๋ฐํ ํ์๋ ํด์ ๋์ง ์์ต๋๋ค. (GC๊ฐ ๋์ค์ ์์์ ํด์ ํฉ๋๋ค.)
The
person
object is not deallocated aftersayHello
returns:
void sayHello(Person person) {
System.out.println("Hello " + person.getName());
}
Memory Management in Rust
๋ฌ์คํธ์ ๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ๋ ์ด์ ๋ฐฉ์๋ค์ ํผํฉํด์ ์ฌ์ฉํฉ๋๋ค:
- ์๋ฐ์ฒ๋ผ ์์ ํ๊ณ ์ ํํฉ๋๋ค. ํ์ง๋ง GC๋ ์์ต๋๋ค.
- C++์ฒ๋ผ ๋ฒ์(์ค์ฝํ)๊ธฐ๋ฐ์ ๋๋ค. ํ์ง๋ง ์ปดํ์ผ๋ฌ๊ฐ ์๊ฒฉํ๊ฒ ์ ์ฉํฉ๋๋ค.
- C/C++์ฒ๋ผ ๋ฐํ์ ์ค๋ฒํค๋1๊ฐ ์์ต๋๋ค.
์ด๋ ๋ฌ์คํธ์ ๋ช
์์ ์ธ ์์ ๊ถ
์ค๊ณ๋ฅผ ํตํด ์ด๋ค์ง๋๋ค.
Memory management in Rust is a mix:
- Safe and correct like Java, but without a garbage collector.
- Scope-based like C++, but the compiler enforces full adherence.
- Has no runtime overhead like in C and C++.
It achieves this by modeling ownership explicitly.
์ญ์ฃผ
๋ฐํ์์์ GC๊ฐ ๋์์ ๋ถํ๊ฐ ๋ฐ์ํฉ๋๋ค. JAVA์ ๊ฒฝ์ฐ ์ข
์ข
ํ๋ก๊ทธ๋จ์ด ํ๋ฆฌ์ฆ๊ฐ ๋๋ ๊ฒ ์ฒ๋ผ ๋ณด์ด๋
๋ ์๋ ํ์์ด ์์ต๋๋ค.
Comparison
๋ฉ๋ชจ๋ฆฌ ๊ด๋ฆฌ ๊ธฐ์ ์ ๋๋ต์ ์ธ ๋น๊ต์ ๋๋ค.
Here is a rough comparison of the memory management techniques.
Pros of Different Memory Management Techniques
- C์ ๊ฐ์ ์๋ ๊ด๋ฆฌ:
- ๋ฐํ์ ์ค๋ฒํค๋๊ฐ ์์.
- JAVA์ ๊ฐ์ ์๋ํ ๊ด๋ฆฌ:
- ์์ ํ ์๋ํ.
- ์์ ํ๊ณ ์ ํํจ.
- C++๊ณผ ๊ฐ์ ๋ฒ์ ๊ธฐ๋ฐ ๊ด๋ฆฌ:
- ๋ถ๋ถ ์๋ํ
- ๋ฐํ์ ์ค๋ฒํค๋๊ฐ ์์.
- ๋ฌ์คํธ์ ๊ฐ์ ์ปดํ์ผ๋ฌ ์ํ ๋ฒ์ ๊ธฐ๋ฐ ๊ด๋ฆฌ:
- ์ปดํ์ผ๋ฌ์ ์ํด ์ํ๋ฉ๋๋ค.
- ๋ฐํ์ ์ค๋ฒํค๋๊ฐ ์์ต๋๋ค.
- ์์ ํ๊ณ ์ ํํฉ๋๋ค.
- Manual like C:
- No runtime overhead.
- Automatic like Java:
- Fully automatic.
- Safe and correct.
- Scope-based like C++:
- Partially automatic.
- No runtime overhead.
- Compiler-enforced scope-based like Rust:
- Enforced by compiler.
- No runtime overhead.
- Safe and correct.
Cons of Different Memory Management Techniques
- C์ ๊ฐ์ ์๋ ๊ด๋ฆฌ:
- ์ฌ์ฉ ํ ํด์ ๋ฌธ์
- ์ด์ค ํด์ ๋ฌธ์
- ๋ฉ๋ชจ๋ฆฌ ๋์ ๋ฌธ์
- JAVA์ ๊ฐ์ ์๋ํ ๊ด๋ฆฌ:
- GC์ ์ผ์์ค์ง
- ์๋ฉธ์ ์ง์ฐ ๋์
- C++๊ณผ ๊ฐ์ ๋ฒ์ ๊ธฐ๋ฐ ๊ด๋ฆฌ:
- ๋ณต์กํ๋ฉฐ ๊ฐ๋ฐ์์ ์ํด์ ์ต์ ํ๊ฐ ํ์ํจ
- ์ฌ์ฉ ํ ํด์ ๋ฌธ์ ๊ฐ๋ฅ์ฑ ์์
- ๋ฌ์คํธ์ ๊ฐ์ ์ปดํ์ผ๋ฌ ์ํ ๋ฒ์ ๊ธฐ๋ฐ ๊ด๋ฆฌ:
- ์ฝ๊ฐ์ ์ด๊ธฐ ๋ณต์ก์ฑ
- ์ ํจํ ํ๋ก๊ทธ๋จ(๋ก์ง)์ด ๊ฑฐ๋ถ ๋ ์ ์์
- Manual like C:
- Use-after-free.
- Double-frees.
- Memory leaks.
- Automatic like Java:
- Garbage collection pauses.
- Destructor delays.
- Scope-based like C++:
- Complex, opt-in by programmer.
- Potential for use-after-free.
- Compiler-enforced and scope-based like Rust:
- Some upfront complexity.
- Can reject valid programs.
Ownership
๋ชจ๋ ๋ณ์ ๋ฐ์ธ๋ฉ์ ์ ํจํ _๋ฒ์_๋ฅผ ๊ฐ์ผ๋ฉฐ, ๋ฒ์ ๋ฐ์์ ๋ณ์ ์ฌ์ฉ์ ์ค๋ฅ์ ๋๋ค:
All variable bindings have a scope where they are valid and it is an error to use a variable outside its scope:
struct Point(i32, i32); fn main() { { let p = Point(3, 4); println!("x: {}", p.0); } // ์ค์ฝํ ์ข ๋ฃ์ง์ println!("y: {}", p.1); } // main ํจ์์ ์ค์ฝํ ์ข ๋ฃ์ง์
- ์ค์ฝํ๊ฐ ์ข ๋ฃ๋๋ฉด ๋ณ์๋ _์ญ์ _๋๊ณ ๋ฐ์ดํฐ ๋ฉ๋ชจ๋ฆฌ๋ ํด์ ๋ฉ๋๋ค.
- ์๋ฉธ์๋ ์ฌ๊ธฐ(์ค์ฝํ ์ข ๋ฃ์ง์ )์์ ๋ฉ๋ชจ๋ฆฌ ์์์ ํด์ ํฉ๋๋ค.
- ์ด๊ฒ์ ๋๊ณ ๋ณ์๊ฐ ๊ฐ์ _์์ _ํ๋ค๊ณ ํํํฉ๋๋ค.
- At the end of the scope, the variable is dropped and the data is freed.
- A destructor can run here to free up resources.
- We say that the variable owns the value.
Move Semantics
(๋ณ์์)ํ ๋น์ ๋ณ์ ๊ฐ ์์ ๊ถ์ ์ด๋์ํต๋๋ค:
An assignment will transfer ownership between variables:
fn main() { let s1: String = String::from("Hello!"); let s2: String = s1; println!("s2: {s2}"); // println!("s1: {s1}"); }
- s1์ s2์ ํ ๋นํ์ฌ ์์ ๊ถ์ ์ด์ ์ํต๋๋ค.
- ๋ฐ์ดํฐ๋ s1์์ _์ด๋_๋ฉ๋๋ค. ๋ฐ๋ผ์ s1์ ๋์ด์ ์ ๊ทผ ํ ์ ์์ต๋๋ค.
s1
์ ์ค์ฝํ๊ฐ ์ข ๋ฃ๋๋ฉด ์๋ฌด ์ผ๋ ์์ต๋๋ค: ์๋ฌด๋ฐ ์์ ๊ถ์ด ์์ต๋๋ค.s2
์ ์ค์ฝํ๊ฐ ์ข ๋ฃ๋๋ฉด ๋ฌธ์์ด ๋ฐ์ดํฐ๋ ํด์ ๋ฉ๋๋ค.- ๊ฐ(๋ฐ์ดํฐ)์ ์์ ๊ถ์ ๊ฐ๋ ๋ณ์๋ ํญ์ ์ ํํ ํ๋ ์ ๋๋ค.
- The assignment of
s1
tos2
transfers ownership.- The data was moved from
s1
ands1
is no longer accessible.- When
s1
goes out of scope, nothing happens: it has no ownership.- When
s2
goes out of scope, the string data is freed.- There is always exactly one variable binding which owns a value.
Moved Strings in Rust
fn main() { let s1: String = String::from("Rust"); let s2: String = s1; }
s1
์ ํ ๋ฐ์ดํฐ๋s2
์์ ์ฌ์ฌ์ฉ ๋ฉ๋๋ค.s1
์ ์ค์ฝํ๊ฐ ์ข ๋ฃ๋๋ฉด ์๋ฌด์ผ๋ ์ผ์ด๋์ง ์์ต๋๋ค.(์ด๋ฏธ ์ด๋๋์์ต๋๋ค.)
- The heap data from
s1
is reused fors2
.- When
s1
goes out of scope, nothing happens (it has been moved from).
s2
์ด๋ ์ ๋ฉ๋ชจ๋ฆฌ:
Before move to
s2
:
s2
์ด๋ ํ ๋ฉ๋ชจ๋ฆฌ:
After move to
s2
:
์ญ์ฃผ
- ์ด๋ ํ ๋ฉ๋ชจ๋ฆฌ ๊ทธ๋ฆผ์์ s1์์ ํ์ผ๋ก ์ฐ๊ฒฐ์ด ์ง์์ก๋ค๊ณ ์ดํดํด๋ ๋ฌด๋ฐฉ์ ํฉ๋๋ค. ์ปดํ์ผ๋ฌ๊ฐ ํ์ธํ๊ธฐ ์ํด ์ ๊ทผ ๋ถ๊ฐ ์ฒ๋ฆฌ ํ ๊ฒ์ผ๋ก ๋ณด์ด๊ธด ํฉ๋๋ค๋งโฆ
Double Frees in Modern C++
Modern C++์ ์ด ๋ฌธ์ ๋ฅผ ๋ค๋ฅด๊ฒ ํด๊ฒฐํฉ๋๋ค:
Modern C++ solves this differently:
std::string s1 = "Cpp";
std::string s2 = s1; // Duplicate the data in s1.
s1
์ ํ ๋ฐ์ดํฐ๋ ๋ณต์ ๋๊ณ ,s2
๋ ๋ ๋ฆฝ์ ์ธ ๋ณต์ฌ๋ณธ์ ์ป์ต๋๋ค.s1
์s2
์ ์ค์ฝํ๊ฐ ์ข ๋ฃ๋๋ฉด ๊ฐ๊ฐ์ ๋ฉ๋ชจ๋ฆฌ๊ฐ ํด์ ๋ฉ๋๋ค.
- The heap data from
s1
is duplicated ands2
gets its own independent copy.- When
s1
ands2
go out of scope, they each free their own memory.
Before copy-assignment:
After copy-assignment:
Moves in Function Calls
๊ฐ์ ํจ์์ ์ ๋ฌํ ๋, ๊ฐ์ ํจ์ ๋งค๊ฐ๋ณ์์ ํ ๋น๋ฉ๋๋ค. ์ด๊ฒ์ ์์ ๊ถ์ ์ด๋์ํต๋๋ค:
When you pass a value to a function, the value is assigned to the function parameter. This transfers ownership:
fn say_hello(name: String) { println!("Hello {name}") } fn main() { let name = String::from("Alice"); say_hello(name); // say_hello(name); // ์ญ์ฃผ: main์๋ name์ ์์ ๊ถ์ด ์์ด ์ฌ ์ ๋ฌ์ด ๋ถ๊ฐ }
Copying and Cloning
์๋ฏธ๊ตฌ์กฐ(Semantics)๊ฐ ์ด๋ํ ๋, ํน์ ํ์ ์ ๊ธฐ๋ณธ์ ์ผ๋ก ๋ณต์ฌ๋ฉ๋๋ค:
While move semantics are the default, certain types are copied by default:
fn main() { let x = 42; let y = x; println!("x: {x}"); println!("y: {y}"); }
์ด๋ฌํ ์ ํ๋ค์ Copy
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํฉ๋๋ค.
์ง์ ๋ง๋ ํ์
๋ค๋ Copy
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ์ฌ ์๋ฏธ๋ณต์ฌ๋ฅผ ํ ์ ์์ต๋๋ค:
These types implement the
Copy
trait.You can opt-in your own types to use copy semantics:
#[derive(Copy, Clone, Debug)] struct Point(i32, i32); fn main() { let p1 = Point(3, 4); let p2 = p1; println!("p1: {p1:?}"); println!("p2: {p2:?}"); }
- ํ ๋น ํ,
p1
์p2
๋ ์์ ์ ๋ฐ์ดํฐ๋ฅผ ์์ ํฉ๋๋ค. - ๋ช
์์ ์ผ๋ก
p1.clone()
๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐ์ดํฐ๋ฅผ ๋ณต์ฌํ ์ ์์ต๋๋ค.
- After the assignment, both
p1
andp2
own their own data.- We can also use
p1.clone()
to explicitly copy the data.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
๋ณต์ฌ์ ๋ณต์ ๋ ๊ฐ์ง ์์ต๋๋ค:
- ๋ณต์ฌ๋ ๋ฉ๋ชจ๋ฆฌ ์์ญ์ ๋นํธ๋จ์ ๋ณต์ฌ๋ณธ์ผ๋ก ์์์ ๊ฐ์ฒด์์๋ ๋์ํ์ง ์์ต๋๋ค.
- ๋ณต์ ๋ ๋ณด๋ค ์ผ๋ฐ์ ์ธ ์์
์ผ๋ก
Clone
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ์ฌ ์ฌ์ฉ์ ์ง์ ๋์์ ํ์ฉํฉ๋๋ค. Drop
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ ํ์ ์์ ๋ณต์ฌ๋ ๋์ํ์ง ์์ต๋๋ค.
Copying and cloning are not the same thing:
- Copying refers to bitwise copies of memory regions and does not work on arbitrary objects.
- Cloning is a more general operation and also allows for custom behavior by implementing the
Clone
trait.- Copying does not work on types that implement the
Drop
trait.
์์ ์์์์ ๋ค์์ ์๋ํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค:
struct Point
๊ตฌ์กฐ์ฒด์String
ํ๋๋ฅผ ์ถ๊ฐํ๋ฉด ์ด๋ป๊ฒ ๋ฉ๋๊น?derive
์์ฑ์์Copy
๋ฅผ ์ ๊ฑฐํด๋ ๋์ํฉ๋๊น?Copy
๋ฅผ ์ ๊ฑฐ ํ ํ,p1
์ ์ด๋ํด๋ ์ฌ์ ํ ์ถ๋ ฅ ๋ฉ๋๊น?
In the above example, try the following:
- What happens when you add a
String
field tostruct Point
?- Does it work when you remove
Copy
from thederive
attribute?- After removing
Copy
, can you still printp1
after the move?
์ญ์ฃผ
#[derive(Copy, Clone, Debug)]
๋ฅผ ํตํด Point ๊ตฌ์กฐ์ฒด๊ฐ Copy๋๋๋ก ํจ
Borrowing
ํจ์ ํธ์ถ์ ๊ฐ์ ์์ ๊ถ์ ์ด๋ํ๋ ๋์ ์ ํจ์๊ฐ ๊ฐ์ _๋น๋ ค_์ฌ ์ ์์ต๋๋ค:
Instead of transferring ownership when calling a function, you can let a function borrow the value:
#[derive(Debug)] struct Point(i32, i32); fn add(p1: &Point, p2: &Point) -> Point { Point(p1.0 + p2.0, p1.1 + p2.1) } fn main() { let p1 = Point(3, 4); let p2 = Point(10, 20); let p3 = add(&p1, &p2); println!("{p1:?} + {p2:?} = {p3:?}"); }
add
ํจ์๋ ๋ Point๊ฐ์ฒด ๊ฐ์ _๋น๋ ค_์ค์์ ์๋ก์ด Point๊ฐ์ฒด๋ฅผ ๋ฐํํฉ๋๋ค.- ํธ์ถ์(main ํจ์)๋ ์ฌ์ ํ p1, p2์ ์์ ๊ถ์ ์ ์งํฉ๋๋ค.
- The
add
function borrows two points and returns a new point.- The caller retains ownership of the inputs.
Shared and Unique Borrows
๋ฌ์คํธ๋ ๊ฐ์ ๋น๋ ค์ค๋ ๋ฐฉ๋ฒ์ ๋ํ ์ ์ฝ์ด ์กด์ฌํฉ๋๋ค:
- ํ๋ฒ์ ํ๋ ์ด์์
&T
๊ฐ์ ๊ฐ์ง ์ ์์ต๋๋ค.(1~N๊ฐ์ ๋ถ๋ณ ๋ณ์) - ๋๋
- ์ ํํ ํ๋์
&mut T
๊ฐ์ ๊ฐ์ง ์ ์์ต๋๋ค.(1๊ฐ์ ๊ฐ๋ณ ๋ณ์)
Rust puts constraints on the ways you can borrow values:
- You can have one or more
&T
values at any given time, or- You can have exactly one
&mut T
value.
fn main() { let mut a: i32 = 10; let b: &i32 = &a; { let c: &mut i32 = &mut a; *c = 20; } println!("a: {a}"); println!("b: {b}"); }
์ญ์ฃผ
- ๋ ์ค ํ๋๋ง ๋ฉ๋๋ค. ๋ฐ๋ผ์ ์ ์์ค๋ ๋ด๋ถ ์ค์ฝํ์์ 1๊ฐ์ ๋ถ๋ณ๋ณ์, 1๊ฐ์ ๊ฐ๋ณ๋ณ์๊ฐ ์กด์ฌํ๊ฒ ๋์ ์ค๋ฅ์ ๋๋ค.
Lifetimes
๋น๋ ค์จ ๊ฐ์ ์๋ช ์ ๊ฐ์ต๋๋ค:
- ์๋ช
๋ ์๋ตํ ์ ์์ต๋๋ค:
add(p1: &Point, p2: &Point) -> Point
. - ๋ฌผ๋ก ๋ช
์ํ ์๋ ์์ต๋๋ค:
&'a Point
,&'document str
. &'a Point
๋ asa
๊ฐ ์ ํจํ ๋์ ๋น๋ ค์จPoint
์ ๋๋ค.- ์๋ช
๋ ํญ์ ์ปดํ์ผ๋ฌ์ ์ํด ์ถ๋ก ๋ฉ๋๋ค.: ์ง์ ์๋ช
์ ์ค์ ํ ์๋ ์์ต๋๋ค.
- ์๋ช
ํ๊ธฐ(
'
)์ ์ ์ฝ์กฐ๊ฑด์ ์์ฑํฉ๋๋ค. - ์ปดํ์ผ๋ฌ๋ ์ ํจํ ์๋ฃจ์ ์ด ์๋์ง ๊ฒ์ฆํฉ๋๋ค.
- ์๋ช
ํ๊ธฐ(
A borrowed value has a lifetime:
- The lifetime can be elided:
add(p1: &Point, p2: &Point) -> Point
.- Lifetimes can also be explicit:
&'a Point
,&'document str
.- Read
&'a Point
as โa borrowedPoint
which is valid for at least the lifetimea
โ.- Lifetimes are always inferred by the compiler: you cannot assign a lifetime yourself.
- Lifetime annotations create constraints; the compiler verifies that there is a valid solution.
์ญ์ฃผ
- ์ ํจํ ์๋ฃจ์ ์ด ์ด๋ค์๋ฏธ์ธ์ง ๋ชจํธํ๋ฐ ์ผ๋จ ๋งค๊ฐ๋ณ์์ ๋ฆฌํด๊ฐ์ ๋ชจ๋ ๊ฐ์ ์๋ช ์ด์ด์ผ ํ๋ค๊ณ ํฉ๋๋ค.
Lifetimes in Function Calls
ํจ์๋ ์ธ์๋ฅผ ๋น๋ฆฌ๋ ๊ฒ ์ธ์๋ ๋น๋ฆฐ ๊ฐ์ ๋ฐํํ ์ ์์ต๋๋ค:
In addition to borrowing its arguments, a function can return a borrowed value:
#[derive(Debug)] struct Point(i32, i32); fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point { if p1.0 < p2.0 { p1 } else { p2 } } fn main() { let p1: Point = Point(10, 10); let p2: Point = Point(20, 20); let p3: &Point = left_most(&p1, &p2); println!("left-most point: {:?}", p3); }
'a
๋ ์ ๋๋ฆญ ๋งค๊ฐ๋ณ์๋ก ์ปดํ์ผ๋ฌ๋ก์ ์ํด ์ถ๋ก ๋ฉ๋๋ค.- ์๋ช
์
'
๋ก ํ๊ธฐํ๋ฉฐ ๋ฌ์คํธ์์๋ ์ผ๋ฐ์ ์ผ๋ก'a
๋ผ๊ณ ํํํฉ๋๋ค. &'a Point
๋ asa
์ ๋์ผํ ์๋ช ์ ๊ฐ์ง๋ ๋น๋ ค์จPoint
์ ๋๋ค.- ์ค์ : ๋ค๋ฅธ ์ค์ฝํ์ ์์ด๋ ์ ์ฉ ๋ฉ๋๋ค.
'a
is a generic parameter, it is inferred by the compiler.- Lifetimes start with
'
and'a
is a typical default name.- Read
&'a Point
as โa borrowedPoint
which is valid for at least the lifetimea
โ.- The at least part is important when parameters are in different scopes.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
์ ์์ ์์ ๋ค์์ ์๋ํด๋ด ๋๋ค:
In the above example, try the following:
p2
์p3
๋ฅผ ์๋ก์ด ๋ฒ์({...}
)๋ก ์๋ ์ฝ๋์ ๊ฐ์ด ์ด๋ํด ๋ด ๋๋ค:
- Move the declaration of
p2
andp3
into a a new scope ({ ... }
), resulting in the following code:
#[derive(Debug)]
struct Point(i32, i32);
fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {
if p1.0 < p2.0 { p1 } else { p2 }
}
fn main() {
let p1: Point = Point(10, 10);
let p3: &Point;
{
let p2: Point = Point(20, 20);
p3 = left_most(&p1, &p2);
}
println!("left-most point: {:?}", p3);
}
p3
๊ฐ p2
๋ณด๋ค ์ค๋ ์ง์๋๊ธฐ ๋๋ฌธ์ ์ด ์์ ๋ ์ปดํ์ผ๋์ง ์์์ ํ์ธํ์๊ธฐ ๋ฐ๋๋๋ค.
Note how this does not compile since
p3
outlivesp2
.
- ์ํฌ์คํ์ด์ค์ ์ด๊ธฐํํ๊ณ ํจ์ ์๊ทธ๋์ฒ๋ฅผ
fn left_most<'a, 'b>(p1:&'a Point, p2:&'a Point) -> &'b Point
๋ก ๋ณ๊ฒฝํฉ๋๋ค.'a
์'b
์ ์๋ช ์ฌ์ด๊ฐ ๋ถ๋ถ๋ช ํ๊ธฐ ๋๋ฌธ์ ์ด๊ฒ์ ์ปดํ์ผ๋์ง ์์ต๋๋ค.
- Reset the workspace and change the function signature to
fn left_most<'a, 'b>(p1: &'a Point, p2: &'a Point) -> &'b Point
. This will not compile because the relationship between the lifetimes'a
and'b
is unclear.
์ญ์ฃผ
- left_mostํจ์๊ฐ ์ข ๋ฃ๋๋๋ผ๋ ๋ฆฌํด๊ฐ p3์ ๋งค๊ฐ๋ณ์์ธ p1,p2์ ๋์ผํ ์๋ช ์ด๋ผ main์์๋ ์ ํจํด์ง๋๋ค.
Lifetimes in Data Structures
๋ง์ฝ ๋น๋ ค์จ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๋ ํ์ (๊ตฌ์กฐ์ฒด ๊ฐ์)์ธ ๊ฒฝ์ฐ, ๋ฐ๋์ ์๋ช ํ๊ธฐ๋ฅผ ํด์ผํฉ๋๋ค.
If a data type stores borrowed data, it must be annotated with a lifetime:
#[derive(Debug)] struct Highlight<'doc>(&'doc str); fn erase(text: String) { println!("Bye {text}!"); } fn main() { let text = String::from("The quick brown fox jumps over the lazy dog."); let fox = Highlight(&text[4..19]); let dog = Highlight(&text[35..43]); // erase(text); println!("{fox:?}"); println!("{dog:?}"); }
์ญ์ฃผ
- Highlight ๊ตฌ์กฐ์ฒด๋ ์ฐธ์กฐ๋ฌธ์์ด(&str)์ ์ ์ฅํฉ๋๋ค. ์๋ ์ถ๋ ฅ๋ฌธ์์ text๋ฅผ ์ถ๋ ฅํด๋ ๋์ผํ๊ฒ ์ ๋ถ ์ถ๋ ฅ๋ฉ๋๋ค.
- ํ์ง๋ง ์ค๊ฐ์ ํ ์คํธ๋ฅผ erase๋ก ์ญ์ ํ๋ ค๊ณ ํ๋ฉด ๋น๋ฆฐ(์ฐธ์กฐ)๊ฐ ์ค์ ๋ ์์ด์ ์์ ๊ถ ์ด๋์ด ๋ถ๊ฐํ๋ค๋ ์๋ฌ๊ฐ ๋ฐ์ํฉ๋๋ค.
- try it!
Day 1: Afternoon Exercises
์ด๋ฒ ์ฐ์ต๋ฌธ์ ๋ ์๋ ๋๊ฐ์ง์ ๋๋ค:
- ์์ ๋์๊ด
- ๋ฐ๋ณต์์ ์์ ๊ถ(์ด๋ ค์!)
We will look at two things:
- A small book library,
- Iterators and ownership (hard).
Designing a Library
์ฐ๋ฆฌ๋ ๋ด์ผ ๊ตฌ์กฐ์ฒด์ Vec<T>
์ ๋ํด ๋ ๋ง์ ๊ฒ์ ๋ฐฐ์ธ ๊ฒ์
๋๋ค.
์ผ๋จ ์ค๋์ API์ ์ผ๋ถ๋ง ์๋ฉด ๋ฉ๋๋ค:
We will learn much more about structs and the
Vec<T>
type tomorrow. For now, you just need to know part of its API:
fn main() { let mut vec = vec![10, 20]; vec.push(30); println!("middle value: {}", vec[vec.len() / 2]); for item in vec.iter() { println!("item: {item}"); } }
๋์๊ด ํ๋ก๊ทธ๋จ์ ๋ง๋ค๊ธฐ ์ํด ์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํด์ ๊ตฌํํ์๋ฉด ๋ฉ๋๋ค.
Use this to create a library application. Copy the code below to https://play.rust-lang.org/ and update the types to make it compile:
// TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] struct Library { books: Vec<Book>, } struct Book { title: String, year: u16, } impl Book { // This is a constructor, used below. fn new(title: &str, year: u16) -> Book { Book { title: String::from(title), year, } } } // This makes it possible to print Book values with {}. impl std::fmt::Display for Book { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} ({})", self.title, self.year) } } impl Library { fn new() -> Library { unimplemented!() } //fn len(self) -> usize { // unimplemented!() //} //fn is_empty(self) -> bool { // unimplemented!() //} //fn add_book(self, book: Book) { // unimplemented!() //} //fn print_books(self) { // unimplemented!() //} //fn oldest_book(self) -> Option<&Book> { // unimplemented!() //} } // ์์ค์ชฝ ์ฃผ์๋ค์ ์ ๊ฑฐํ๊ณ ๋๋ฝ๋ ๋ฉ์๋๋ฅผ ๊ตฌํํ์ธ์. // ๋ฉ์๋ ์ ์๋ ์์ ๋์ด์ผ ํฉ๋๋ค.(self๊ฐ ํฌํจ๋๋๋ก) // This shows the desired behavior. Uncomment the code below and // implement the missing methods. You will need to update the // method signatures, including the "self" parameter! fn main() { let library = Library::new(); //println!("Our library is empty: {}", library.is_empty()); // //library.add_book(Book::new("Lord of the Rings", 1954)); //library.add_book(Book::new("Alice's Adventures in Wonderland", 1865)); // //library.print_books(); // //match library.oldest_book() { // Some(book) => println!("My oldest book is {book}"), // None => println!("My library is empty!"), //} // //println!("Our library has {} books", library.len()); }
์ญ์ฃผ
- ๊ฐ์๋ฅผ ๋์ผ๋ก๋ง ๋ณด๊ณ ์์๋ค๋ฉด ํฌ๊ฒ์ดํธ๊ฐ ๋ ์ ์์ต๋๋ค.
- ๊ธฐ๋ณธ์ ์ผ๋ก ์ด ๊ฐ์๋ ์ฃผ์ด์ง ๋ด์ฉ์ ์ถ๊ฐ๋ก ์ฐพ์๋ณด๊ณ ๊ณต์๋ฌธ์ ๋ณด๊ณ ์์ ์ด๊ฒ์ ๊ฒ ๋ง์ ธ๋ณด๊ณ ํด๋ด์ผ ๋ฐ๋ผ์ฌ ์ ์์ต๋๋ค.
ํํธ
- ์ฌ์ค ๋๋ถ๋ถ ์ปดํ์ผ๋ฌ๊ฐ ์๋ฌ ๋ด๋ฉด์ ์ด๋ ๊ฒ ํ์ธ์ ํ๋๊น ๋์ด๋๋ ์ฝ์ต๋๋ค.
- ์ค์ ๋ก ํด๋ณด๋ main์๋ ์์ ์ ํ๋๋ก ์ปดํ์ผ๋ฌ๊ฐ ์๋์ ์ฃผ๋ค์โฆ
- ๊ทผ๋ฐ ๊ณต์๋ฌธ์์์ ํ์ํ ๋ฉ์๋๋ค์ ์ฐพ์์ ํ์ด์ผ ํฉ๋๋ค. ๋ฌผ๋ก ide์์ ๋์์คํ
์ง๋ง ํ๋ ์ด๊ทธ๋ผ์ด๋์๋ ๊ทธ๋ฐ๊ฑฐ ์์โฆ
- ๋ฒกํฐ(Vec
) ๋ณด๋ค๋ ์ดํฐ๋ ์ดํฐ(Iter()) ์ชฝ์ ์ข ๋ ๋ด์ผํ ๋ฏ.
- ๋ฒกํฐ(Vec
- ํด๋ก์ (์ต๋ช
ํจ์)๋ฅผ ์จ์ผ ํ๋ค๊ฑฐ๋ ํด์ ๋ฌธ๋ฒ์ ๊ฐ๋ตํ ์ฐ๋ฉด
|param| param.item
ํ์์ ๋๋ค.- js์์๋
param => param.item
์ ํด๋นํฉ๋๋ค.
- js์์๋
Iterators and Ownership
๋ฌ์คํธ์ ์์ ๊ถ ๋ชจ๋ธ์ ๋ง์ API์ ์ํฅ์ ์ค๋๋ค.
์๋ฅผ๋ค์ด Iterator
์ IntoIterator
๊ฐ์ ํธ๋ ์ดํธ๊ฐ ์์ต๋๋ค.
The ownership model of Rust affects many APIs. An example of this is the
Iterator
andIntoIterator
traits.
Iterator
ํธ๋ ์ดํธ๋ ํ์ ์ ๋ํ ํ๋(๋ฉ์๋)๋ฅผ ์ค๋ช ํ๋ค๋ ์ ์์ ์ธํฐํ์ด์ค์ ์ ์ฌํฉ๋๋ค.
Iterator
๋ ๋จ์ํ None
๊ฐ ๋์ฌ๋๊น์ง next
๋ฅผ ํธ์ถํ๋ ํธ๋ ์ดํธ์
๋๋ค.
Traits are like interfaces: they describe behavior (methods) for a type. The
Iterator
trait simply says that you can callnext
until you getNone
back:
#![allow(unused)] fn main() { pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } }
Iterator
ํธ๋ ์ดํธ๋ ์ด๋ ๊ฒ ์ฌ์ฉํฉ๋๋ค:
You use this trait like this:
fn main() { let v: Vec<i8> = vec![10, 20, 30]; let mut iter = v.iter(); println!("v[0]: {:?}", iter.next()); println!("v[1]: {:?}", iter.next()); println!("v[2]: {:?}", iter.next()); println!("No more items: {:?}", iter.next()); }
์ง๋ฌธ) ๋ฐ๋ณต์(์ดํฐ๋ ์ดํฐ)๊ฐ ๋ฐํํ๋ ํ์ ์ ๋ฌด์์ ๋๊น? ์๋ ์ฝ๋๋ฅผ ์์ ํด๋ณด์ธ์:
What is the type returned by the iterator? Test your answer here:
fn main() { let v: Vec<i8> = vec![10, 20, 30]; let mut iter = v.iter(); let v0: Option<..> = iter.next(); println!("v0: {v0:?}"); }
์ ์ด๋ฐ ๊ฒ์ ์ฌ์ฉํด์ผ ํฉ๋๊น?
Why is this type used?
IntoIterator
Iterator
ํธ๋ ์ดํธ๋ ์์ฑ๋ ๋ฐ๋ณต์๋ฅผ โ์ด๋ป๊ฒ ๋ฐ๋ณต ํ๋์งโ ์๋ ค์ค๋๋ค.
์ ์ฌํ IntoIterator
ํธ๋ ์ดํธ๋ โ๋ฐ๋ณต์๋ฅผ ์ด๋ป๊ฒ ๋ง๋๋์งโ ์๋ ค์ค๋๋ค.
The
Iterator
trait tells you how to iterate once you have created an iterator. The related traitIntoIterator
tells you how to create the iterator:
#![allow(unused)] fn main() { pub trait IntoIterator { type Item; type IntoIter: Iterator<Item = Self::Item>; fn into_iter(self) -> Self::IntoIter; } }
IntoIterator
์ ๋ชจ๋ ๊ตฌํ์ ๋ฐ๋์ ๋ ํ์
์ ์ ์ธํด์ผํฉ๋๋ค:
Item
:i8
๊ณผ ๊ฐ์ด ๋ฐ๋ณต๋๋ ์์์ ์ ํIntoIter
:into_iter
๋ฉ์๋์์ ๋ฐํ๋๋Iterator
ํ์
IntoIter
์ Item
๋ ๋งํฌ๋์ด ์์ต๋๋ค: ๋ฐ๋ณต์์ Item
ํ์
์ ๋์ผํด์ผํฉ๋๋ค. ์ฆ, Option<Item>
๋ฅผ ๋ฐํํด์ผ ํฉ๋๋ค.
The syntax here means that every implementation of
IntoIterator
must declare two types:
Item
: the type we iterate over, such asi8
,IntoIter
: theIterator
type returned by theinto_iter
method. Note thatIntoIter
andItem
are linked: the iterator must have the sameItem
type, which means that it returnsOption<Item>
์ง๋ฌธ) (์ด์ ๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก) ๋ฐ๋ณต์(์ดํฐ๋ ์ดํฐ)๊ฐ ๋ฐํํ๋ ํ์ ์ ๋ฌด์์ ๋๊น? ์๋ ์ฝ๋๋ฅผ ์์ ํด๋ณด์ธ์: Like before, what is the type returned by the iterator?
fn main() { let v: Vec<String> = vec![String::from("foo"), String::from("bar")]; let mut iter = v.into_iter(); let v0: Option<..> = iter.next(); println!("v0: {v0:?}"); }
for
Loops
์, ์ด์ ์ฐ๋ฆฌ๋ Iterator
์ IntoIterator
๋ฅผ ์์์ผ๋ฏ๋ก for
๋ฃจํ๋ฅผ ๋ง๋ค ์ ์์ต๋๋ค.
for
๋ฃจํ๋ into_iter()
๋ฅผ ํธ์ถํ์ฌ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ ๊ฒ์ ๋ฐ๋ณตํฉ๋๋ค:
Now that we know both
Iterator
andIntoIterator
, we can buildfor
loops. They callinto_iter()
on an expression and iterates over the resulting iterator:
fn main() { let v: Vec<String> = vec![String::from("foo"), String::from("bar")]; for word in &v { println!("word: {word}"); } for word in v { println!("word: {word}"); } }
์ง๋ฌธ) ๋งค ๋ฃจํ์์ word
์ ํ์
์ ๋ฌด์์
๋๊น?
What is the type of
word
in each loop?
์ ์ฝ๋์์ ์คํ ํด ๋ณธ ํ ๋ค์ ๋ฌธ์๋ฅผ ์ฐธ์กฐํด์ ๋ต๋ณ์ ํ์ธํ์๊ธฐ ๋ฐ๋๋๋ค.
Experiment with the code above and then consult the documentation for
impl IntoIterator for &Vec<T>
andimpl IntoIterator for Vec<T>
to check your answers.
Welcome to Day 2
์๋นํ ๋ถ๋์ ๋ฌ์คํธ์ ๋ํด ๋ณด์๊ณ , ์ด์ด์ ์ค๋ ๊ฐ์๋ฅผ ์งํํ๊ฒ ์ต๋๋ค:
-
๊ตฌ์กฐ์ฒด, ์ด๊ฑฐํ, ๋ฉ์๋
-
ํจํด ๋งค์นญ: ์ด๊ฑฐํ, ๊ตฌ์กฐ์ฒด ๊ทธ๋ฆฌ๊ณ ๋ฐฐ์ด ๋ถํด
-
ํ๋ฆ ์ ์ด:
if
,if let
,while
,while let
,break
, ๊ทธ๋ฆฌ๊ณcontinue
. -
ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ::
String
,Option
๊ณผResult
,Vec
,HashMap
,Rc
๊ทธ๋ฆฌ๊ณArc
. -
๋ชจ๋: ๊ฐ์์ฑ, ๊ฒฝ๋ก ๋ฐ ํ์ผ ์์คํ ๊ณ์ธต.
Now that we have seen a fair amount of Rust, we will continue with:
Structs, enums, methods.
Pattern matching: destructuring enums, structs, and arrays.
Control flow constructs:
if
,if let
,while
,while let
,break
, andcontinue
.The Standard Library:
String
,Option
andResult
,Vec
,HashMap
,Rc
andArc
.Modules: visibility, paths, and filesystem hierarchy.
Structs
C/C++๊ณผ ๋ง์ฐฌ๊ฐ์ง๋ก ๋ฌ์คํธ๋ ์ปค์คํ ๊ตฌ์กฐ์ฒด๋ฅผ ์ง์ํฉ๋๋ค:
Like C and C++, Rust has support for custom structs:
struct Person { name: String, age: u8, } fn main() { let peter = Person { name: String::from("Peter"), age: 27, }; println!("{} is {} years old", peter.name, peter.age); }
Tuple Structs
๊ฐ ๊ฐ์ ์ด๋ฆ์ด ์ค์ํ์ง ์๋ค๋ฉด ํ๋ธ ๊ตฌ์กฐ์ฒด๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค:
If the field names are unimportant, you can use a tuple struct:
struct Point(i32, i32); fn main() { let p = Point(17, 23); println!("({}, {})", p.0, p.1); }
์ข ์ข ๋จ์ผ ํ๋์ ๋ํผ(wrapper)๋ก ์ฌ์ฉ๋ฉ๋๋ค.(๋ฌ์คํธ์์ newtypes ํจํด1์ด๋ผ ๋ถ๋ฆ ๋๋ค):
This is often used for single-field wrappers (called newtypes):
struct PoundOfForce(f64); struct Newtons(f64); fn compute_thruster_force() -> PoundOfForce { todo!("Ask a rocket scientist at NASA") } fn set_thruster_force(force: Newtons) { // ... } fn main() { let force = compute_thruster_force(); set_thruster_force(force); }
์ญ์ฃผ
๊ฐ ์์ฒด๊ฐ ์๋ฏธ๋ฅผ ๊ฐ์ง๋ ๊ฒฝ์ฐ(cm, mm, kg ๋ฑ)์ ์ด๋ฅผ ํ๊ธฐํ๊ธฐ ์ํด ๋จ์ผ ๊ฐ์ ๋ํํ๋ ํจํด์ ๋๋ค.(์์๋ ๋ฌผ๋ฆฌ ๋จ์(๋ดํด, ํ์ด๋(ํ))๋ฅผ ๋ํํ๊ณ ์์ต๋๋ค. )
Field Shorthand Syntax
๊ตฌ์กฐ์ฒด ํ๋์ ๋์ผํ ์ด๋ฆ์ ๋ณ์๊ฐ ์๋ค๋ฉด ์๋์ ๊ฐ์ด ์งง์ ๋ฌธ๋ฒ ์ผ๋ก ๊ตฌ์กฐ์ฒด๋ฅผ ์์ฑํ ์ ์์ต๋๋ค:
If you already have variables with the right names, then you can create the struct using a shorthand:
#[derive(Debug)] struct Person { name: String, age: u8, } impl Person { fn new(name: String, age: u8) -> Person { Person { name, age } // <-- ์ด๋ถ๋ถ } } fn main() { let peter = Person::new(String::from("Peter"), 27); println!("{peter:?}"); }
Enums
enum
ํค์๋๋ ์ด๊ฑฐํ ํ์
์ ์์ฑํฉ๋๋ค:
The
enum
keyword allows the creation of a type which has a few different variants:
fn generate_random_number() -> i32 { 4 // Chosen by fair dice roll. Guaranteed to be random. } #[derive(Debug)] enum CoinFlip { Heads, Tails, } fn flip_coin() -> CoinFlip { let random_number = generate_random_number(); if random_number % 2 == 0 { return CoinFlip::Heads; } else { return CoinFlip::Tails; } } fn main() { println!("You got: {:?}", flip_coin()); }
์ญ์ฃผ
- variants: ์ด๊ฑฐํ์ ์์๋ค์ ๋งํฉ๋๋ค ์ด๊ฑฐํ์ ๊ฐ์ variants์ค ํ๋์ฌ์ผ ํฉ๋๋ค.
Variant Payloads
๋ค์ํ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ง variants
๋ฅผ ์ด๊ฑฐํ์ ์ ์ํ๊ณ , match
๊ตฌ๋ฌธ์ ์ด์ฉํด ์ด๋ฅผ ์ถ์ถํ ์ ์์ต๋๋ค:
You can define richer enums where the variants carry data. You can then use the
match
statement to extract the data from each variant:
enum WebEvent { PageLoad, // Variant without payload KeyPress(char), // Tuple struct variant Click { x: i64, y: i64 }, // Full struct variant } #[rustfmt::skip] fn inspect(event: WebEvent) { match event { WebEvent::PageLoad => println!("page loaded"), WebEvent::KeyPress(c) => println!("pressed '{c}'"), WebEvent::Click { x, y } => println!("clicked at x={x}, y={y}"), } } fn main() { let load = WebEvent::PageLoad; let press = WebEvent::KeyPress('x'); let click = WebEvent::Click { x: 20, y: 80 }; inspect(load); inspect(press); inspect(click); }
์ญ์ฃผ
- ์ด๊ฑฐํ ์์์ ๊ฐ์ ํฌํจํ๋๋ก(์์) ์ ์ธํด์ match ๋ฌธ์์ ์ด๊ฑฐํ์ ํ์ ์ ๋ฐ๋ผ ๋์ํ๋๋ก ๋ง๋ค์ด์ง ์์์ ๋๋ค
Enum Sizes
๋ฌ์คํธ์ ์ด๊ฑฐํ์ ์ ๋ ฌ๋ก ์ธํ ์ ์ฝ์ ๊ณ ๋ คํ์ฌ ํฌ๊ธฐ๋ฅผ ๋นฝ๋นฝํ๊ฒ ์ก์ต๋๋ค
Rust enums are packed tightly, taking constraints due to alignment into account:
use std::mem::{align_of, size_of}; macro_rules! dbg_size { ($t:ty) => { println!("{}: size {} bytes, align: {} bytes", stringify!($t), size_of::<$t>(), align_of::<$t>()); }; } enum Foo { A, B, } fn main() { dbg_size!(Foo); }
-
์์ธํ ์ฌํญ์ ๊ณต์๋ฌธ์๋ฅผ ํ์ธํ์ธ์.
-
See the Rust Reference.
Methods
๋ฌ์คํธ์์ ์ ์ธ๋ ํ์
์ ๋ํด impl
๋ธ๋ก์ ํจ์๋ฅผ ์ ์ธํ์ฌ ๋ฉ์๋๋ฅผ ์ฐ๊ฒฐํ ์ ์์ต๋๋ค:
Rust allows you to associate functions with your new types. You do this with an
impl
block:
#[derive(Debug)] struct Person { name: String, age: u8, } impl Person { fn say_hello(&self) { println!("Hello, my name is {}", self.name); } } fn main() { let peter = Person { name: String::from("Peter"), age: 27, }; peter.say_hello(); }
Method Receiver
&self
๋ ๋ฉ์๋๊ฐ ๊ฐ์ฒด๋ฅผ ๋ถ๋ณํ๊ฒ ๋น๋ ค์ด์ ๋ํ๋
๋๋ค. ๊ทธ ์ธ์ ๋ฉ์๋๊ฐ ๋ฐ์์ฌ ์ ์๋ ์ธ์๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
&self
: ํธ์ถ์๋ก๋ถํฐ ๋ถ๋ณ์ฐธ์กฐ๊ฐ์ฒด๋ฅผ ๋น๋ ค์ด์ ๋ํ๋ ๋๋ค. ๊ฐ์ฒด๋ ๋์ค์ ๋ค์ ์ฌ์ฉ ๋ ์ ์์ต๋๋ค.&mut self
: ํธ์ถ์๋ก๋ถํฐ ๊ฐ๋ณ์ฐธ์กฐ๊ฐ์ฒด๋ฅผ ๋น๋ ค์ด์ ๋ํ๋ ๋๋ค. ๊ฐ์ฒด๋ ๋์ค์ ๋ค์ ์ฌ์ฉ ๋ ์ ์์ต๋๋ค.self
: ํธ์ถ์์ ๊ฐ์ฒด๊ฐ ์ด๋๋์ด ๋ฉ์๋๊ฐ ๊ฐ์ฒด์ ์์ ๊ถ์ ๊ฐ์ ธ์ต๋๋ค. ๋ฐ๋ผ์ ๋ช ์์ ์ผ๋ก ์์ ๊ถ์ ๋ฐํํ์ง ์์ผ๋ฉด (๋ฉ์๋ ์ข ๋ฃ ํ)๊ฐ์ฒด๋ ์ญ์ (ํด์ )๋ฉ๋๋ค.- ์ธ์ ์์: ๊ตฌ์กฐ์ฒด์ ์ ์ ๋ฉ์๋๊ฐ ๋ฉ๋๋ค. ๊ด์ต์ ์ผ๋ก
new
๋ผ๊ณ ์ง์ ๋๋ ์์ฑ์๋ฅผ ๋ง๋ค๋ ์ฌ์ฉํฉ๋๋ค.
self
์ ๋ํ variants ใ
์ธ์๋ Box<Self>
์ ๊ฐ์ด ์ธ์ ์ ํ์ผ๋ก ํ์ฉ๋๋ special wrapper types๋ ์์ต๋๋ค.
The
&self
above indicates that the method borrows the object immutably. There are other possible receivers for a method:
&self
: borrows the object from the caller using a shared and immutable reference. The object can be used again afterwards.&mut self
: borrows the object from the caller using a unique and mutable reference. The object can be used again afterwards.self
: takes ownership of the object and moves it away from the caller. The method becomes the owner of the object. The object will be dropped (deallocated) when the method returns, unless its ownership is explicitly transmitted.- No receiver: this becomes a static method on the struct. Typically used to create constructors which are called
new
by convention.Beyond variants on
self
, there are also special wrapper types allowed to be receiver types, such asBox<Self>
.
Example
#[derive(Debug)] struct Race { name: String, laps: Vec<i32>, } impl Race { // ์ด ๋ฉ์๋๋ self๊ฐ ์์ต๋๋ค. ์ด๊ฒ์ ์ ์ ๋ฉ์๋ ์ ๋๋ค. // No receiver, a static method fn new(name: &str) -> Race { Race { name: String::from(name), laps: Vec::new() } } // ์ด ๋ฉ์๋๋ self์ ๋ํ ๋ ์ ์ ์ธ ์ฝ๊ธฐ-์ฐ๊ธฐ ๊ถํ์ ๊ฐ์ต๋๋ค. // Exclusive borrowed read-write access to self fn add_lap(&mut self, lap: i32) { self.laps.push(lap); } // ์ด ๋ฉ์๋๋ self ๋ํ ๊ณต์ ๋ฐ ์ฝ๊ธฐ์ ์ฉ ๋น๋ฆผ ๊ถํ์ ๊ฐ์ต๋๋ค. // Shared and read-only borrowed access to self fn print_laps(&self) { println!("Recorded {} laps for {}:", self.laps.len(), self.name); for (idx, lap) in self.laps.iter().enumerate() { println!("Lap {idx}: {lap} sec"); } } // ์ด ๋ฉ์๋๋ self์ ์์ ๊ถ์ ๊ฐ์ ธ์ต๋๋ค. // self๋ฅผ ๋ฐํํ์ง ์๊ธฐ ๋๋ฌธ์ ์ด ๋ฉ์๋๊ฐ ํธ์ถ ๋ ํ main์์ race ์ฌ์ฌ์ฉ ํ ์ ์์ต๋๋ค. // Exclusive ownership of self fn finish(self) { let total = self.laps.iter().sum::<i32>(); println!("Race {} is finished, total lap time: {}", self.name, total); } } fn main() { let mut race = Race::new("Monaco Grand Prix"); race.add_lap(70); race.add_lap(68); race.print_laps(); race.add_lap(71); race.print_laps(); race.finish(); }
Pattern Matching
match
ํค์๋๋ C/C++์ switch
์ ์ ์ฌํ๊ฒ ํ๋ ์ด์์ ํจํด๊ณผ ์ผ์น ์ํฌ ์ ์์ต๋๋ค.
๋น๊ต๋์์ ์์์ ์๋๋ก ์งํ๋๋ฉฐ ์ฒ์ ์ผ์นํ๋ ํจํด์ด ์คํ๋ฉ๋๋ค.
The
match
keyword let you match a value against one or more patterns. The comparisons are done from top to bottom and the first match wins.The patterns can be simple values, similarly to
switch
in C and C++:
fn main() { let input = 'x'; match input { 'q' => println!("Quitting"), 'a' | 's' | 'w' | 'd' => println!("Moving around"), '0'..='9' => println!("Number input"), _ => println!("Something else"), } }
_
ํจํด์ ์ด๋ค ํจํด๊ณผ๋ ๋งค์นญ๋๋ ์์ผ๋ ์นด๋์
๋๋ค.(default)
The
_
pattern is a wildcard pattern which matches any value.
Destructuring Enums
๊ตฌ์กฐ์ฒด์ ๋ฐ์ธ๋ฉ๋ ๊ฐ์ ํจํด์ผ๋ก ์ฌ์ฉํ ์ ์์ต๋๋ค. ๊ฐ๋จํ enum
ํ์
์ ์์์
๋๋ค:
Patterns can also be used to bind variables to parts of your values. This is how you inspect the structure of your types. Let us start with a simple
enum
type:
enum Result { Ok(i32), Err(String), } fn divide_in_two(n: i32) -> Result { if n % 2 == 0 { Result::Ok(n / 2) } else { Result::Err(format!("cannot divide {} into two equal parts", n)) } } fn main() { let n = 100; match divide_in_two(n) { Result::Ok(half) => println!("{n} divided in two is {half}"), Result::Err(msg) => println!("sorry, an error happened: {msg}"), } }
์์ match
๊ตฌ๋ฌธ์ divide_in_two
ํจ์์์ ๋ฐํ๋๋ Result
๊ฐ์ arm1์ผ๋ก ๋ถํดํฉ๋๋ค.
- ์ฒซ๋ฒ์งธ arm์
half
๋Ok
variant์ ๋ฐ์ธ๋ฉ๋ ๊ฐ์ ๋๋ค.(n/2)
- ๋๋ฒ์งธ amr์
msg
๋Err
variant์ ๋ฐ์ธ๋ฉ ๋ ์๋ฌ ๋ฉ์์ง ์ ๋๋ค.
Here we have used the arms to destructure the
Result
value. In the first arm,half
is bound to the value inside theOk
variant. In the second arm,msg
is bound to the error message.
์ญ์ฃผ 1: match์ ํจํด ์ค ํ๋์ ๋๋ค. (switch์ case์ ํด๋น)
Destructuring Structs
๊ตฌ์กฐ์ฒด
์ญ์ ๋ถํดํ ์ ์์ต๋๋ค:
You can also destructure
structs
:
struct Foo { x: (u32, u32), y: u32, } #[rustfmt::skip] fn main() { let foo = Foo { x: (1, 2), y: 3 }; match foo { Foo { x: (1, b), y } => println!("x.0 = 1, b = {b}, y = {y}"), Foo { y: 2, x: i } => println!("y = 2, i = {i:?}"), Foo { y, .. } => println!("y = {y}, other fields were ignored"), } }
Destructuring Arrays
๋ฐฐ์ญ ์ญ์ ๋ถํด๊ฐ ๊ฐ๋ฅํ๊ณ , ์ฌ๋ผ์ด์ค๋ฅผ ์ ์ฉํ ์ ์์ต๋๋ค.
You can destructure arrays, tuples, and slices by matching on their elements:
#[rustfmt::skip] fn main() { let triple = [0, -2, 3]; println!("Tell me about {triple:?}"); match triple { [0, y, z] => println!("First is 0, y = {y}, and z = {z}"), [1, ..] => println!("First is 1 and the rest were ignored"), _ => println!("All elements were ignored"), } }
Match Guards
match๋ฅผ ์ฌ์ฉํ ๋ ๊ฐ ํจํด์ ๋ํด์ ๋ถ๋ฆฌ์ธ์ผ๋ก ๋ฐํ๋๋ ๊ฒ์ฌ์(guard)๋ฅผ ์ถ๊ฐํ ์ ์์ต๋๋ค.
When matching, you can add a guard to a pattern. This is an arbitrary Boolean expression which will be executed if the pattern matches:
#[rustfmt::skip] fn main() { let pair = (2, -2); println!("Tell me about {pair:?}"); match pair { (x, y) if x == y => println!("These are twins"), (x, y) if x + y == 0 => println!("Antimatter, kaboom!"), (x, _) if x % 2 == 1 => println!("The first one is odd"), _ => println!("No correlation..."), } }
Day 2: Morning Exercises
์ด๋ฒ ์ฐ์ต๋ฌธ์ ๋ค์ ๋๊ฐ์ง ๋งฅ๋ฝ์์ ๋ฉ์๋ ๊ตฌํ๋ฐฉ๋ฒ์ ๋ค๋ฃน๋๋ค:
- ๊ฑด๊ฐ ์ํ ํต๊ณ๋ฅผ ์ถ์ ํ๋ ํ๋ก๊ทธ๋จ์ ๊ฐ๋จํ ๊ตฌ์กฐ์ฒด.
- ๋๋ก์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ํ ๋ค์ค ๊ตฌ์กฐ์ฒด ๋ฐ ์ด๊ฑฐํ.
We will look at implementing methods in two contexts:
- Simple struct which tracks health statistics.
- Multiple structs and enums for a drawing library.
Health Statistics
๋น์ ์ ๊ฑด๊ฐ ์ํ๋ฅผ ๋ชจ๋ํฐ๋งํ๋ ์์คํ ์ ๊ตฌํํ๋ ์ผ์ ํ๊ณ ์์ต๋๋ค. ๊ทธ ์ผํ์ผ๋ก ๋น์ ์ ์ฌ์ฉ์์ ๊ฑด๊ฐ ์ํ ํต๊ณ๋ฅผ ์ถ์ ํด์ผํฉ๋๋ค.
Youโre working on implementing a health-monitoring system. As part of that, you need to keep track of usersโ health statistics.
๋น์ ์ ๋ชฉํ๋ User
๊ตฌ์กฐ์ฒด์ impl
๋ธ๋ก์ ๋น ํจ์fmf ๊ตฌํํ๋ ๊ฒ์
๋๋ค.
Youโll start with some stubbed functions in an
impl
block as well as aUser
struct definition. Your goal is to implement the stubbed out methods on theUser
struct
defined in theimpl
block.
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํด์ ๋น ์ง ๋ฉ์๋๋ฅผ ๊ตฌํํ์๋ฉด ๋ฉ๋๋ค:
Copy the code below to https://play.rust-lang.org/ and fill in the missing methods:
// TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] struct User { name: String, age: u32, weight: f32, } impl User { pub fn new(name: String, age: u32, weight: f32) -> Self { unimplemented!() } pub fn name(&self) -> &str { unimplemented!() } pub fn age(&self) -> u32 { unimplemented!() } pub fn weight(&self) -> f32 { unimplemented!() } pub fn set_age(&mut self, new_age: u32) { unimplemented!() } pub fn set_weight(&mut self, new_weight: f32) { unimplemented!() } } fn main() { let bob = User::new(String::from("Bob"), 32, 155.2); println!("I'm {} and my age is {}", bob.name(), bob.age()); } #[test] fn test_weight() { let bob = User::new(String::from("Bob"), 32, 155.2); assert_eq!(bob.weight(), 155.2); } #[test] fn test_set_age() { let mut bob = User::new(String::from("Bob"), 32, 155.2); assert_eq!(bob.age(), 32); bob.set_age(33); assert_eq!(bob.age(), 33); }
์ญ์ฃผ
- ๋ฑํ ๋์ด๋๊ฐ ์๋ ๋ฌธ์ ๋ผ ํํธ๋ ์์ต๋๋ค.
- ํ๋ ์ด๊ทธ๋ผ์ด๋ ๊ธฐ์ค warning์ด ์ข ์๋๋ฐ ํ ์คํธ๋ ์คํ์ ์ ์์ด๋ค์
Polygon Struct
์ฐ๋ฆฌ๋ ๋ช๊ฐ์ ๊ผญ์ง์ ์ ๊ฐ์ง ๋ค๊ฐํ
์ ํํํ๋ ๊ตฌ์กฐ์ฒด๋ฅผ ๋ง๋ค ๊ฒ์
๋๋ค.
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํด์ ํ ์คํธ๊ฐ ํต๊ณผํ๋๋ก ๋น ์ง ๋ฉ์๋๋ฅผ ๊ตฌํํ์๋ฉด ๋ฉ๋๋ค:
We will create a
Polygon
struct which contain some points. Copy the code below to https://play.rust-lang.org/ and fill in the missing methods to make the tests pass:
// TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] pub struct Point { // add fields } impl Point { // add methods } pub struct Polygon { // add fields } impl Polygon { // add methods } pub struct Circle { // add fields } impl Circle { // add methods } pub enum Shape { Polygon(Polygon), Circle(Circle), } #[cfg(test)] mod tests { use super::*; fn round_two_digits(x: f64) -> f64 { (x * 100.0).round() / 100.0 } #[test] fn test_point_magnitude() { let p1 = Point::new(12, 13); assert_eq!(round_two_digits(p1.magnitude()), 17.69); } #[test] fn test_point_dist() { let p1 = Point::new(10, 10); let p2 = Point::new(14, 13); assert_eq!(round_two_digits(p1.dist(p2)), 5.00); } #[test] fn test_point_add() { let p1 = Point::new(16, 16); let p2 = p1 + Point::new(-4, 3); assert_eq!(p2, Point::new(12, 19)); } #[test] fn test_polygon_left_most_point() { let p1 = Point::new(12, 13); let p2 = Point::new(16, 16); let mut poly = Polygon::new(); poly.add_point(p1); poly.add_point(p2); assert_eq!(poly.left_most_point(), Some(p1)); } #[test] fn test_polygon_iter() { let p1 = Point::new(12, 13); let p2 = Point::new(16, 16); let mut poly = Polygon::new(); poly.add_point(p1); poly.add_point(p2); let points = poly.iter().cloned().collect::<Vec<_>>(); assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]); } #[test] fn test_shape_circumferences() { let mut poly = Polygon::new(); poly.add_point(Point::new(12, 13)); poly.add_point(Point::new(17, 11)); poly.add_point(Point::new(16, 16)); let shapes = vec![ Shape::from(poly), Shape::from(Circle::new(Point::new(10, 20), 5)), ]; let circumferences = shapes .iter() .map(Shape::circumference) .map(round_two_digits) .collect::<Vec<_>>(); assert_eq!(circumferences, vec![15.48, 31.42]); } } #[allow(dead_code)] fn main() {}
์ญ์ฃผ
- ๊ตฌํ์ฒด์ +(Add), -(Sub)๊น์ง ๊ตฌํํ๊ฒ ๋ง๋ค์๋๋ฐ ๋์ด๋๊ฐ ๊ฝค ๋์ต๋๋ค
- shape์ ๊ด๋ จ๋ impl๋ ๊ตฌํํด์ผํฉ๋๋ค.
- ์ผ๋จ ์คํํด์ ์ปดํ์ผ๋ฌ ์ค๋ฅ๋ฅผ ์ก์๊ฐ๋ TDD๋ก ์งํํด์ผ ๊ทธ๋๋ง(โฆ) ์์ํ๋ค์
ํํธ- ํฌ์ธํธ ์ฐ์ฐ ํจ์, shape from ํจ์
#![allow(unused)] fn main() { impl std::ops::Add for Point { type Output = Self; fn add(self, other: Self) -> Self::Output { Self { x: self.x + other.x, y: self.y + other.y, } } } impl std::ops::Sub for Point { type Output = Self; fn sub(self, other: Self) -> Self::Output { Self { x: self.x - other.x, y: self.y - other.y, } } } impl From<Polygon> for Shape { fn from(poly: Polygon) -> Self { Shape::Polygon(poly) } } impl From<Circle> for Shape { fn from(circle: Circle) -> Self { Shape::Circle(circle) } } }
ํํธ- ๊ตฌํํจ์ ์ค๋ช
- point.magnitude : (0,0)๊ณผ point์ ๊ฑฐ๋ฆฌ
- point.dist: ์ ๋ ฅ๋ฐ์ ํฌ์ธํธ์ point ์ฌ์ด์ ๊ฑฐ๋ฆฌ
- shape.circumference: ํ ๋๋ฆฌ ๊ธธ์ด(๋ค๊ฐํ), ๋๋ (์)
ํํธ- ์ฐธ์กฐํ ์์ํจ์ ์ค๋ช
- ๊ณต์์ ์๋ตํฉ๋๋ค(..)
- ์ ๊ณฑ์ฐ์ฐ
- f64::๋ฃจํธ
- PI :
std::f64::consts::PI
Control Flow
์์์ ์ดํด๋ณธ ๋ฐ์ ๊ฐ์ด ๋ฌ์คํธ์ ํํ์์ผ๋ก์จ if
๋ ๋ ๋ธ๋ก ์ค ํ๋๋ฅผ ์กฐ๊ฑด์ ๋ฐ๋ผ ํ๊ฐ(๋ฐํ)ํ๋ฉฐ, ๋ธ๋ก์ if
ํํ์์ ๊ฐ์ด ๋๋ ๊ฐ์ ๊ฐ์ง ์ ์์ต๋๋ค. ๋ค๋ฅธ ํ๋ฆ์ ์ด ํํ์๋ ๋ฌ์คํธ์์ ์ ์ฌํ๊ฒ ์๋ํฉ๋๋ค.
As we have seen,
if
is an expression in Rust. It is used to conditionally evaluate one of two blocks, but the blocks can have a value which then becomes the value of theif
expression. Other control flow expressions work similarly in Rust.
Blocks
๋ฌ์คํธ์์ ๋ธ๋ก์ ๊ฐ๊ณผ ํ์ ์ ๊ฐ์ต๋๋ค: ๋ธ๋ก์ ํํ์์ด ๊ฐ์ด ๋ฉ๋๋ค.
A block in Rust has a value and a type: the value is the last expression of the block:
fn main() { let x = { let y = 10; println!("y: {y}"); let z = { let w = { 3 + 4 }; println!("w: {w}"); y * w }; println!("z: {z}"); z - y }; println!("x: {x}"); }
ํจ์์๋ ๋์ผํ ๊ท์น์ด ์ ์ฉ๋ฉ๋๋ค: ํจ์๋ฐ๋์ (๋ง์ง๋ง) ๊ฐ์ด ๋ฐํ ๊ฐ์ด ๋ฉ๋๋ค.
The same rule is used for functions: the value of the function body is the return value:
fn double(x: i32) -> i32 { x + x } fn main() { println!("doubled: {}", double(7)); }
์ญ์ฃผ
- ๋ง์ง๋ง ์ค์ ; ์๋ ๋ถ๋ถ์ ๊ตฌ๋ฌธ(statements)์ด ์๋๋ผ ํํ์(expressions)์ด๋ผ๊ณ ํฉ๋๋ค.
- ๋ธ๋ก์์ ๊ตฌ๋ฌธ+ ๋ง์ง๋ง ํํ์ ์ธ๊ฒฝ์ฐ ํด๋น ํจ์๋ฅผ ํํ์์ผ๋ก ๋ด ๋๋ค.
if
expressions
if
๋ฌธ์ ๋ค๋ฅธ ์ธ์ด์ ๋์ผํ๊ฒ ์ฌ์ฉํ ์ ์์ต๋๋ค(์กฐ๊ฑด์ ()๋ ์์ต๋๋ค):
You use
if
very similarly to how you would in other languages:
fn main() { let mut x = 10; if x % 2 == 0 { x = x / 2; } else { x = 3 * x + 1; } }
๊ฒ๋ค๊ฐ if
๋ ํํ์(ํ ๋น๊ฐ๋ฅ)์ผ๋ก ์ฌ์ฉ ๋ ์๋ ์์ต๋๋ค.
์๋ ์ฝ๋๋ ์์ ๋์ผํ ๊ฒฐ๊ณผ ์
๋๋ค.
In addition, you can use it as an expression. This does the same as above:
fn main() { let mut x = 10; x = if x % 2 == 0 { x / 2 } else { 3 * x + 1 }; }
if let
expressions
if let
๋ฌธ์ ์ฌ์ฉํ๋ฉด ๊ฐ์ ํจํด๋งค์นญ์ ์ฌ์ฉํ ์ ์์ต๋๋ค:
If you want to match a value against a pattern, you can use
if let
:
fn main() { let arg = std::env::args().next(); if let Some(value) = arg { println!("Program name: {value}"); } else { println!("Missing name?"); } }
๋ฌ์คํธ์ ํจํด๋งค์นญ์ ์ฐธ์กฐํ์ธ์
See pattern matching for more details on patterns in Rust.
while
expressions
while
์ญ์ ๋ค๋ฅธ ์ธ์ด์ ๋์ผํ ์ฌ์ฉ๋ฒ์ ๊ฐ์ต๋๋ค:
The
while
keyword works very similar to other languages:
fn main() { let mut x = 10; while x != 1 { x = if x % 2 == 0 { x / 2 } else { 3 * x + 1 }; } println!("Final x: {x}"); }
while let
expressions
if
์ ๋์ผํ๊ฒ while let
๊ตฌ๋ฌธ ์ญ์ ํจํด๋งค์นญ์ ์ฌ์ฉ ํ ์ ์์ต๋๋ค.
Like with
if
, there is awhile let
variant which repeatedly tests a value against a pattern:
fn main() { let v = vec![10, 20, 30]; let mut iter = v.into_iter(); while let Some(x) = iter.next() { println!("x: {x}"); } }
v.iter()
๊ฐ ๋ฐํํ ๋ฐ๋ณต์๋ next()
๊ฐ ํธ์ถ๋ ๋๋ง๋ค Option<i32>
๋ฅผ ๋ฐํํฉ๋๋ค.
์ด๋ None
์ด ํธ์ถ๋๊ธฐ ์ ๊น์ง Some(x)
๋ฅผ ๋ฐํํ๋ค๋ ์๋ฏธ๋ก ๊ฒฐ๊ณผ์ ์ผ๋ก while let
์ ๋ฐ๋ณต์์ ๋ชจ๋ ์์ดํ
์ ๋ฐ๋ณตํ๋๋ก ํ๊ฒ ํด์ค๋๋ค.
๋ฌ์คํธ์ ํจํด๋งค์นญ์ ์ฐธ์กฐํ์ธ์
Here the iterator returned by
v.iter()
will return aOption<i32>
on every call tonext()
. It returnsSome(x)
until it is done, after which it will returnNone
. Thewhile let
lets us keep iterating through all items.See pattern matching for more details on patterns in Rust.
for
expressions
for
ํํ์์ while let
ํํ์๊ณผ ๋งค์ฐ ์ ์ฌํฉ๋๋ค. for
ํํ์์ ์๋์ผ๋ก into_iter()
๋ฅผ ํธ์ถํ ๋ค์ ์ด๋ฅผ ๋ฐ๋ณตํฉ๋๋ค.
The
for
expression is closely related to thewhile let
expression. It will automatically callinto_iter()
on the expression and then iterate over it:
fn main() { let v = vec![10, 20, 30]; for x in v { println!("x: {x}"); } }
์ญ์ ๋ค๋ฅธ์ธ์ด์ ๋ง์ฐฌ๊ฐ์ง๋ก break
์ continue
๋ฅผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
You can use
break
andcontinue
here as usual.
loop
expressions
๋ง์ง๋ง์ผ๋ก loop
ํค์๋๋ ๋ฌดํํ ๋ฃจํ๋ฅผ ์์ฑํฉ๋๋ค. ๋ฐ๋ผ์ ๋ฐ๋์ break
๋๋ return
๋ฅผ ์ฌ์ฉํด์ ๋ฃจํ๋ฅผ ์ ์งํด์ผ ํฉ๋๋ค:
Finally, there is a
loop
keyword which creates an endless loop. Here you must eitherbreak
orreturn
to stop the loop:
fn main() { let mut x = 10; loop { x = if x % 2 == 0 { x / 2 } else { 3 * x + 1 }; if x == 1 { break; } } println!("Final x: {x}"); }
match
expressions
๋ง์น if let
๋ฅผ ์ฌ๋ฌ๊ฐ ์ ์ฉํ ๊ฒ๊ณผ ๊ฐ์ด match
ํค์๋๋ ํ๋ ์ด์์ ํจํด์ ์ฐพ๋๋ฐ ์ฌ์ฉ๋ฉ๋๋ค.
The
match
keyword is used to match a value against one or more patterns. In that sense, it works like a series ofif let
expressions:
fn main() { match std::env::args().next().as_deref() { Some("cat") => println!("Will do cat things"), Some("ls") => println!("Will ls some files"), Some("mv") => println!("Let's move some files"), Some("rm") => println!("Uh, dangerous!"), None => println!("Hmm, no program name?"), _ => println!("Unknown program name!"), } }
if let
์ฒ๋ผ ๊ฐ ๋งค์น ์(match arm)์ ๋ง์ง๋ง ํํ์์ด ํ์
์ด ๋๋ฉฐ ๋ชจ๋ ์์ ๋์ผํ ํ์
์ด์ด์ผ ํฉ๋๋ค. ์์ ์์ ์์ ํ์
์ ()
(๋ฐํ๊ฐ ์์)์
๋๋ค.
๋ฌ์คํธ์ ํจํด๋งค์นญ์ ์ฐธ์กฐํ์ธ์
Like if let
, each match arm must have the same type. The type is the last
expression of the block, if any. In the example above, the type is ()
.
See pattern matching for more details on patterns in Rust.
์ญ์ฃผ
- ์๋ฌธ์ด ์ข ๋ํดํ๋ฐ, ์์์์ ๊ฐ ์์ ํ์
์ ๋ฆฌํด ์์(์ถ๋ ฅ๋ง ํ๊ณ ๋)์
๋๋ค(๋ฌ์คํธ์์
()
๋ผ๊ณ ํฉ๋๋ค.ํจ์
์์ค ์ค๊ฐ ์ฃผ์ ์ฐธ์กฐ) - ๊ฐ ์๋ ๋ธ๋ก
{}
์ผ๋ก ํํ๊ฐ๋ฅํ๊ณ ์ด ์ญ์ ํจ์์ฒ๋ผ ๋ง์ง๋ง ํํ์์ผ๋ก ๋ฆฌํด ์ํฌ ์ ์๋๋ฐ ์ด๋ฅผ ๊ฐ ์์ ํ์ ์ผ๋ก ํ๋ค๋ ์๋ฏธ. - ์์ ๋ฅผ ์ฌ๋ฌ ๋ฐํ์์ผ๋ก ํ ์คํธ ํด๋ณด์๊ธฐ ๋ฐ๋๋๋ค.
break
and continue
๋ง์ฝ ๋ฃจํ๋ฅผ ์ค๊ฐ์ ๋ฉ์ถ๊ณ ์ญ๋ค๋ฉด break
๋ฅผ, ๋ฐ๋ก ๋ค์ ๋ฐ๋ณต์ผ๋ก ๋์ด๊ฐ๊ธฐ ์ํด์๋ continue
๋ฅผ ์ฌ์ฉํฉ๋๋ค. ๋ ํค์๋ ๋ชจ๋ ์ค์ฒฉ ๋ฃจํ์์ label๋ก ํ๊ธฐํ ์ธ์๋ฅผ ์ทจํ์ฌ ์ ์ด ํ ์ ์์ต๋๋ค.
If you want to exit a loop early, use
break
, if you want to immediately start the next iteration usecontinue
. Bothcontinue
andbreak
can optionally take a label argument which is used to break out of nested loops:
fn main() { let v = vec![10, 20, 30]; let mut iter = v.into_iter(); 'outer: while let Some(x) = iter.next() { println!("x: {x}"); let mut i = 0; while i < x { println!("x: {x}, i: {i}"); i += 1; if i == 3 { break 'outer; } } } }
์ ์์ ๋ ์ค์ ๋ฃจํ๋ฅผ 3ํ ๋ฐ๋ณตํ ํ ๋ฐ๊นฅ๋ฃจํ(โouterโ ๋ ์ด๋ธ)์ ์ ์งํฉ๋๋ค.(์ข ๋ฃ)
In this case we break the outer loop after 3 iterations of the inner loop.
Standard Library
๋ฌ์คํธ๋ ๋ฌ์คํธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ํ๋ก๊ทธ๋จ์์ ์ฌ์ฉ๋๋ ๊ณตํต ํ์
์ ์ค์ ํ๋ ๋ฐ ๋์์ ์ฃผ๋ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ํจ๊ป ์ ๊ณต ๋ฉ๋๋ค. ์ด๋ ๊ฒ ํ๋ฉด ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ชจ๋ ๊ฐ์ String
ํ์
์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ์ํํ๊ฒ ํจ๊ป ์๋ํ ์ ์์ต๋๋ค.
Rust comes with a standard library which helps establish a set of common types used by Rust library and programs. This way, two libraries can work together smoothly because they both use the same
String
type.
์ผ๋ฐ์ ์ธ ํ์ ์ ์๋์ ๊ฐ์ต๋๋ค:
The common vocabulary types include:
Option
andResult
ํ์ : ์ ํ์ ์ต์ ๊ฐ๊ณผ error handling์ ์ฌ์ฉ๋ฉ๋๋ค.String
: ์์ ๋ฐ์ดํฐ์์ ์ฌ์ฉ๋๋ ๊ธฐ๋ณธ์ ์ธ ๋ฌธ์์ด ํ์ ์ ๋๋ค.Vec
: ํ์ฅ๊ฐ๋ฅํ ํ์ค ๋ฒกํฐ ํ์ ์ ๋๋ค.HashMap
: ๊ตฌ์ฑ ๊ฐ๋ฅํ ํด์ ์๊ณ ๋ฆฌ์ฆ์ ๊ฐ์ง๋ ํด์ฌ ๋งต ํ์ ์ ๋๋คBox
: ํ์ ํ ๋น๋ ๋ฐ์ดํฐ์ ๋ํ ์์ ํฌ์ธํฐ์ ๋๋ค.Rc
: ํ์ ํ ๋น๋ ๋ฐ์ดํฐ์ ๋ํ ์ฐธ์กฐ ์นด์ดํ ๊ณต์ ํฌ์ธํธ์ ๋๋ค.
Option
andResult
types: used for optional values and error handling.String
: the default string type used for owned data.Vec
: a standard extensible vector.HashMap
: a hash map type with a configurable hashing algorithm.Box
: an owned pointer for heap-allocated data.Rc
: a shared reference-counted pointer for heap-allocated data.
String
String
์ ํ์ ํ ๋น๋ ํ์ฅ๊ฐ๋ฅํ ํ์ค UTF-8 ๋ฌธ์์ด ๋ฒํผ์
๋๋ค.
String
is the standard heap-allocated growable UTF-8 string buffer:
fn main() { let mut s1 = String::new(); s1.push_str("Hello"); println!("s1: len = {}, capacity = {}", s1.len(), s1.capacity()); let mut s2 = String::with_capacity(s1.len() + 1); s2.push_str(&s1); s2.push('!'); println!("s2: len = {}, capacity = {}", s2.len(), s2.capacity()); }
String
์ Deref<Target = str>
์ ๊ตฌํํฉ๋๋ค.
์ด๋ , String
์์ ๋ชจ๋ str
๊ด๋ จ ๋ฉ์๋๋ฅผ ํธ์ถ ํ ์ ์๋ค๋ ์๋ฏธ ์
๋๋ค.
String
implementsDeref<Target = str>
, which means that you can call allstr
methods on aString
.
Option
and Result
์ด ํ์ ์ ์ ํ๊ฐ๋ฅํ ๋ฐ์ดํฐ๋ฅผ ํ์ํฉ๋๋ค:
The types represent optional data:
fn main() { let numbers = vec![10, 20, 30]; let first: Option<&i8> = numbers.first(); println!("first: {first:?}"); let idx: Result<usize, usize> = numbers.binary_search(&10); println!("idx: {idx:?}"); }
Vec
Vec
๋ ํ ํ ๋น๋ ํ์ค ๊ฐ๋ณํฌ๊ธฐ ๋ฒํผ์
๋๋ค.
Vec
is the standard resizable heap-allocated buffer:
fn main() { let mut numbers = Vec::new(); numbers.push(42); let mut v1 = Vec::new(); v1.push(42); println!("v1: len = {}, capacity = {}", v1.len(), v1.capacity()); let mut v2 = Vec::with_capacity(v1.len() + 1); v2.extend(v1.iter()); v2.push(9999); println!("v2: len = {}, capacity = {}", v2.len(), v2.capacity()); }
Vec
์ Deref<Target = [T]>
๋ฅผ ๊ตฌํํฉ๋๋ค.
์ด๋ Vec
์์ ์ฌ๋ผ์ด์ค ๋ฉ์๋(๋ฐฐ์ด ๊ด๋ จ ๋ฉ์๋)๋ฅผ ํธ์ถ ํ ์ ์๋ค๋ ์๋ฏธ์
๋๋ค.
Vec
implementsDeref<Target = [T]>
, which means that you can call slice methods on aVec
.
HashMap
HashDoS1 ๊ณต๊ฒฉ์ผ๋ก๋ถํฐ ๋ณดํธ๋๋ ํ์ค ํด์ ๋งต์ ๋๋ค.
Standard hash map with protection against HashDoS attacks:
use std::collections::HashMap; fn main() { let mut page_counts = HashMap::new(); page_counts.insert("Adventures of Huckleberry Finn".to_string(), 207); page_counts.insert("Grimms' Fairy Tales".to_string(), 751); page_counts.insert("Pride and Prejudice".to_string(), 303); if !page_counts.contains_key("Les Misรฉrables") { println!("We've know about {} books, but not Les Misรฉrables.", page_counts.len()); } for book in ["Pride and Prejudice", "Alice's Adventure in Wonderland"] { match page_counts.get(book) { Some(count) => println!("{book}: {count} pages"), None => println!("{book} is unknown.") } } }
์ญ์ฃผ
Hash table์ ์ฌ์ฉํ๋ ์น์๋ฒ์ ํ๋ผ๋ฏธํฐ๊ฐ ๋ง์ POST๋ฅผ ํธ์ถํ์ฌ Hash table ์ถฉ๋์ ์ ๋ํ์ฌ CPU ๋ถํ๋ฅผ ๋ฐ์์ํค๋ ๊ณต๊ฒฉ ๋ฐฉ๋ฒ.
- POST, GET ์์ฒญ์ ํ๋ผ๋ฉํฐ์ ๋น ๋ฅธ ์ ๊ทผ์ ์ํด ์น์๋ฒ๋ ํ๋ผ๋ฉํฐ๋ฅผ Hash table๋ก ๊ด๋ฆฌํ๋๋ฐ, POST ์์ฒญ์ ์ ๋ฌํ ์ ์๋ ํ๋ผ๋ฉํฐ์ ์์ ์ ํ์ด ์๋ค๋ ์ ์ ์ด์ฉํ ๊ณต๊ฒฉ ๋ฐฉ๋ฒ
Box
Box
๋ ํ ๋ฐ์ดํฐ์ ๋ํ ์์ ํฌ์ธํฐ์
๋๋ค:
Box
is an owned pointer to data on the heap:
fn main() { let five = Box::new(5); println!("five: {}", *five); }
Box<T>
์ Deref<Target = T>
๋ฅผ ๊ตฌํํฉ๋๋ค.
์ด๋ Box<T>
์์ T ๊ด๋ จ ๋ฉ์๋๋ฅผ ์ง์ ํธ์ถ ํ ์ ์๋ค๋ ์๋ฏธ์
๋๋ค.
Box<T>
implementsDeref<Target = T>
, which means that you can call methods fromT
directly on aBox<T>
.
์ญ์ฃผ
- ์ผ์ข ์ ๋ํ ๊ฐ์ฒด๋ผ์ ํ์ ์ ๋ด๋ โ์์โ ๋ผ๋ ์๋ฏธ์ธ๋ฏ ํฉ๋๋ค.
Box with Recursive Data Structures
์ฌ๊ท ๋ฐ์ดํฐ๋ ๋์ ํฌ๊ธฐ์ ๋ฐ์ดํฐ ํ์
์ Box
ํ์
์ ์ฌ์ฉํด์ผ ํฉ๋๋ค.
Recursive data types or data types with dynamic sizes need to use a
Box
:
#[derive(Debug)] enum List<T> { Cons(T, Box<List<T>>), Nil, } fn main() { let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); println!("{list:?}"); }
Niche Optimization
#[derive(Debug)] enum List<T> { Cons(T, Box<List<T>>), Nil, } fn main() { let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil)))); println!("{list:?}"); }
Box
๋ ๋น์ด์์ ์ ์์ต๋๋ค. ๋ฐ๋ผ์ ํฌ์ธํธ๋ ํญ์ ์ ํจํ๊ณ null
์ด ์๋๋๋ค.
์ด๋ ์ปดํ์ผ๋ฌ๊ฐ ๋ฉ๋ชจ๋ฆฌ ๋ ์ด์์์ ์ต์ ํ ํ ์ ์๊ฒ ํด์ค๋๋ค.
A
Box
cannot be empty, so the pointer is always valid and non-null
. This allows the compiler to optimize the memory layout:
Rc
Rc
๋ ์ฐธ์กฐ ์นด์ดํ
๊ณต์ ํฌ์ธํธ์
๋๋ค.
์ฌ๋ฌ ์์น์ ๋์ผํ ๋ฐ์ดํฐ๋ฅผ ์ฐธ์กฐํด์ผํ ๊ฒฝ์ฐ ์ฌ์ฉํฉ๋๋ค:
Rc
is a reference-counted shared pointer. Use this when you need to refer to the same data from multiple places:
use std::rc::Rc; fn main() { let mut a = Rc::new(10); let mut b = a.clone(); println!("a: {a}"); println!("b: {b}"); }
Rc
๋ด๋ถ์ ๋ฐ์ดํฐ๋ฅผ ๋ณ๊ฒฝํด์ผ ํ๋ ๊ฒฝ์ฐ, ๋ฐ์ดํฐ๋ฅผ Cell
๋๋ RefCell
๋ก ๋ํํด์ผํฉ๋๋ค.
๋ฉํฐ์ค๋ ๋์ธ ๊ฒฝ์ฐ Arc
์ฐธ์กฐ
If you need to mutate the data inside an
Rc
, you will need to wrap the data in a type such asCell
orRefCell
. SeeArc
if you are in a multi-threaded context.
Modules
impl
๋ธ๋ก์ ๋ค์์คํ์ด์คํจ์๋ฅผ ํ์
์ผ๋ก ์ ๊ณตํฉ๋๋ค. mod
์ญ์ ๋ค์์คํ์ด์ค ํ์
๊ณผ ํจ์๋ฅผ ์ ๊ณตํฉ๋๋ค:
We have seen how
impl
blocks let us namespace functions to a type. Similarly,mod
lets us namespace types and functions:
mod foo { pub fn do_something() { println!("In the foo module"); } } mod bar { pub fn do_something() { println!("In the bar module"); } } fn main() { foo::do_something(); bar::do_something(); }
Visibility
๋ชจ๋์ ๊ธฐ๋ณธ ์ ๊ทผ์๋ private ์ ๋๋ค:
- ๋ชจ๋์ ํญ๋ชฉ์ ๊ธฐ๋ณธ์ ์ผ๋ก private ์ ๋๋ค.(๊ตฌํ์์ ์จ๊ฒจ์ง)
- ๋ถ๋ชจ์ ์ด์ ํญ๋ชฉ์์๋ ์ ๊ทผ ๊ฐ๋ฅํฉ๋๋ค.
Modules are a privacy boundary:
- Module items are private by default (hides implementation details).
- Parent and sibling items are always visible.
mod outer { fn private() { println!("outer::private"); } pub fn public() { println!("outer::public"); } mod inner { fn private() { println!("outer::inner::private"); } pub fn public() { println!("outer::inner::public"); super::private(); } } } fn main() { outer::public(); }
Paths
๊ฒฝ๋ก๋ ์๋์ ๊ฐ์ด ๊ตฌ๋ถํฉ๋๋ค:
- ์๋๊ฒฝ๋ก
foo
๋๋self::foo
๋foo
๋ชจ๋ ์์์ ํ์ฌ ๋ชจ๋์ ๊ฐ๋ฆฌํต๋๋ค.super::foo
๋foo
๋ชจ๋์ ๋ถ๋ชจ ๋ชจ๋์ ๊ฐ๋ฆฌํต๋๋ค.
- ์ ๋ ๊ฒฝ๋ก
crate::foo
๋ ํ์ฌ ํฌ๋ ์ดํธ ๋ฃจํธ์ ์๋foo
๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.bar::foo
๋bar
ํฌ๋ ์ดํธ ์์ ์๋foo
๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
Paths are resolved as follows:
As a relative path:
foo
orself::foo
refers tofoo
in the current module,super::foo
refers tofoo
in the parent module.As an absolute path:
crate::foo
refers tofoo
in the root of the current crate,bar::foo
refers tofoo
in thebar
crate.
์ญ์ฃผ
- crate: ๋ฌ์คํธ์ ๊ธฐ๋ณธ ํจํค์ง ํน์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋จ์์ ๋๋ค. std๋ฅผ ๊ธฐ๋ณธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ / ๊ธฐ๋ณธ ํฌ๋ ์ดํธ ๋ผ๊ณ ํฉ๋๋ค.
Filesystem Hierarchy
๋ชจ๋์ ๋ด์ฉ์ ์๋ต๋ ์ ์์ต๋๋ค:
The module content can be omitted:
mod garden;
garden
๋ชจ๋์ ๋ด์ฉ์ ์๋ ์์น์์ ํ์ธ ํ ์ ์์ต๋๋ค.
The
garden
module content is found at:
src/garden.rs
(modern Rust 2018 style)src/garden/mod.rs
(older Rust 2015 style)
์ ์ฌํ๊ฒ garden::vegetables
๋ชจ๋์ ์๋ ์์น์์ ํ์ธํ ์ ์์ต๋๋ค.
Similarly, a
garden::vegetables
module can be found at:
src/garden/vegetables.rs
(modern Rust 2018 style)src/garden/vegetables/mod.rs
(older Rust 2015 style)
crate
(ํฌ๋ ์ดํธ)์ ๋ฃจํธ๋ ์๋ ๊ฒฝ๋ก ์
๋๋ค:
The
crate
root is in:
src/lib.rs
(for a library crate)src/main.rs
(for a binary crate)
Day 2: Afternoon Exercises
์ด๋ฒ ์ฐ์ต๋ฌธ์ ๋ ๋ฌธ์์ด๊ณผ ๋ฐ๋ณต์์ ์ด์ ์ ๋ง์ถ ๊ฒ์ ๋๋ค.
The exercises for this afternoon will focus on strings and iterators.
Luhn Algorithm
๋ฃฌ ์๊ณ ๋ฆฌ์ฆ์ ์ ์ฉ์นด๋ ๋ฒํธ ๊ฒ์ฆ์ ์ฌ์ฉ๋๋ ์๊ณ ๋ฆฌ์ฆ ์
๋๋ค.
์ด ์๊ณ ๋ฆฌ์ฆ์ ์ ์ฉ์นด๋ ๋ฒํธ๋ฅผ ๋ฌธ์์ด
๋ก ์
๋ ฅ๋ฐ๊ณ , ์๋์ ์์์ ๋ฐ๋ผ ์ ์ฉ์นด๋ ๋ฒํธ์ ์ ํจ์ฑ์ ํ์ธํฉ๋๋ค:
The Luhn algorithm is used to validate credit card numbers. The algorithm takes a string as input and does the following to validate the credit card number:
- ๋ชจ๋ ๊ณต๋ฐฑ์ ๋ฌด์ํฉ๋๋ค, 2์๋ฆฌ ๋ฏธ๋ง ์ซ์๋ ๋ฌด์ํฉ๋๋ค.
- ์ค๋ฅธ์ชฝ์์ ์ผ์ชฝ์ผ๋ก ์ด๋ํ๋ฉฐ 2๋ฒ์งธ ์๋ฆฌ๋ง๋ค ์ซ์๋ฅผ 2๋ฐฐ ์ฆ๊ฐ์ํต๋๋ค.
1234
์์ 3๊ณผ 1์ ๋๋ฐฐ๋ก ๋ง๋ญ๋๋ค.(2464) - ๋๋ฐฐ๋ก ๋ง๋ ์ซ์๊ฐ 2์๋ฆฌ๊ฐ ๋์ผ๋ฉด ๊ฐ ์๋ฆฌ๋ฅผ ๋ํฉ๋๋ค:
7
์ ๋๋ฐฐ๋14
์ด๋ฏ๋ก5
๊ฐ ๋ฉ๋๋ค. - ๋ชจ๋ ์๋ฆฌ์ ์ซ์๋ฅผ ํฉํฉ๋๋ค.
- ํฉ๊ณ์ ๋์๋ฆฌ๊ฐ
0
์ธ ๊ฒฝ์ฐ ์ ํจํ ์ ์ฉ์นด๋ ๋ฒํธ ์ ๋๋ค.
- Ignore all spaces. Reject number with less than two digits.
- Moving from right to left, double every second digit: for the number
1234
, we double3
and1
.- After doubling a digit, sum the digits. So doubling
7
becomes14
which becomes5
.- Sum all the undoubled and doubled digits.
- The credit card number is valid if the sum is ends with
0
.
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํ๊ณ ํจ์๋ฅผ ๊ตฌํํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค.
Copy the following code to https://play.rust-lang.org/ and implement the function:
// TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] pub fn luhn(cc_number: &str) -> bool { unimplemented!() } #[test] fn test_non_digit_cc_number() { assert!(!luhn("foo")); } #[test] fn test_empty_cc_number() { assert!(!luhn("")); assert!(!luhn(" ")); assert!(!luhn(" ")); assert!(!luhn(" ")); } #[test] fn test_single_digit_cc_number() { assert!(!luhn("0")); } #[test] fn test_two_digit_cc_number() { assert!(luhn(" 0 0 ")); } #[test] fn test_valid_cc_number() { assert!(luhn("4263 9826 4026 9299")); assert!(luhn("4539 3195 0343 6467")); assert!(luhn("7992 7398 713")); } #[test] fn test_invalid_cc_number() { assert!(!luhn("4223 9826 4026 9299")); assert!(!luhn("4539 3195 0343 6476")); assert!(!luhn("8273 1232 7352 0569")); } #[allow(dead_code)] fn main() {}
์ญ์ฃผ
- ๊ด๋ จ ๋ฉ์๋ ํ์ธ์ ์ํ ๊ณต์๋ฌธ์ ์์นญ๋ง ์ข ํ๋ฉด ๋จ์ํ ์คํธ๋ง ํ์ฑ ์๊ณ ๋ฆฌ์ฆ์ด๋ผโฆ
Strings and Iterators
์ด๋ฒ ํ๋ จ์ ์น ์๋ฒ์ ๋ผ์ฐํ ์ปดํฌ๋ํธ๋ฅผ ๊ตฌํํฉ๋๋ค. ์๋ฒ๋ _์์ฒญ๊ฒฝ๋ก(request path)_์ ์ผ์นํ๋ ์ฌ๋ฌ๊ฐ์ _๊ฒฝ๋ก ์ ๋์ฌ(path prefixes)_๋ก ๊ตฌ์ฑ๋์ด ์์ต๋๋ค. ๊ฒฝ๋ก ์ ๋์ฌ์๋ ์์ผ๋์นด๋๋ฌธ์๋ฅผ ํฌํจํ ์ ์์ต๋๋ค. ์๋ ํ ์คํธ ์ฝ๋๋ฅผ ์ฐธ์กฐํ์ธ์
In this exercise, you are implementing a routing component of a web server. The server is configured with a number of path prefixes which are matched against request paths. The path prefixes can contain a wildcard character which matches a full segment. See the unit tests below.
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํ๊ณ ํ
์คํธ๋ฅผ ํต๊ณผํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค. ์ค๊ฐ ๊ฒฐ๊ณผ๊ฐ์ Vec
์ ํ ๋นํ์ง ์๋๋ก ์ฃผ์ ํ์๊ธฐ ๋ฐ๋๋๋ค.
Copy the following code to https://play.rust-lang.org/ and make the tests pass. Try avoiding allocating a
Vec
for your intermediate results:
#![allow(unused)] fn main() { // TODO: remove this when you're done with your implementation. #![allow(unused_variables, dead_code)] pub fn prefix_matches(prefix: &str, request_path: &str) -> bool { unimplemented!() } #[test] fn test_matches_without_wildcard() { assert!(prefix_matches("/v1/publishers", "/v1/publishers")); assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc-123")); assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc/books")); assert!(!prefix_matches("/v1/publishers", "/v1")); assert!(!prefix_matches("/v1/publishers", "/v1/publishersBooks")); assert!(!prefix_matches("/v1/publishers", "/v1/parent/publishers")); } #[test] fn test_matches_with_wildcard() { assert!(prefix_matches( "/v1/publishers/*/books", "/v1/publishers/foo/books" )); assert!(prefix_matches( "/v1/publishers/*/books", "/v1/publishers/bar/books" )); assert!(prefix_matches( "/v1/publishers/*/books", "/v1/publishers/foo/books/book1" )); assert!(!prefix_matches("/v1/publishers/*/books", "/v1/publishers")); assert!(!prefix_matches( "/v1/publishers/*/books", "/v1/publishers/foo/booksByAuthor" )); } }
์ญ์ฃผ
- ๋จ์ ํ์ฑ์ธ๋ฐ ์ ์ฝ์กฐ๊ฑด์ ์ฃผ์ ํ์ธ์. (Vec ์ฌ์ฉ๊ธ์ง)
- match ํ์ฉ์ธ๋ฐ ๊ฐ์ธ์ ์ผ๋ก ์ข ๋ฎ์ ๋ฐฉ๋ฒ์ด๋ผ ์ต์ํด์ง ํ์๊ฐ ์์ต๋๋ค.
ํํธ
- iter ๊ณต์ ๋ฌธ์ ์ฐธ์กฐ
- solution์ ์์๋ฅผ Option์ผ๋ก ๊ฐ์ธ๊ณ ๋ง์ง๋ง์ None์ผ๋ก ๋๊ณ match๋ฌธ์ ์ฌ์ฉํ๋ ๋ก์ง์ ๋๋ค.
Welcome to Day 3
์ด๋ฒ ๊ฐ์๋ Rust์ ๋ฉฐ๊ฐ์ง ๊ณ ๊ธ ์ฃผ์ ๋ฅผ ๋ค๋ฃน๋๋ค:
- ํธ๋ ์ดํธ: ํธ๋ ์ดํธ ํ์(derive), ๊ธฐ๋ณธ ๋ฉ์๋, ์ฃผ์ ํ์ค๋ผ์ด๋ธ๋ฌ๋ฆฌ ํธ๋ ์ดํธ
- ์ ๋๋ฆญ: ์ ๋๋ฆญ ๋ฐ์ดํฐ ํ์ , ์ ๋๋ฆญ ๋ฉ์๋, ๋จํํ(monomorphization), ๊ทธ๋ฆฌ๊ณ ํธ๋ ์ดํธ ๊ฐ์ฒด
- ์ค๋ฅ์ฒ๋ฆฌ(์๋ฌ ํธ๋ค๋ง): ํจ๋,
Result
,?
์ฐ์ฐ์(์ํ ์ฐ์ฐ์) - ํ ์คํธ: ๋จ์ ํ ์คํธ, ๋ฌธ์ ํ ์คํธ ๋ฐ ํตํฉ ํ ์คํธ
- ์์ ํ์ง ์์ ๋ฌ์คํธ: ์์(raw) ํฌ์ธํฐ, ์ ์ ๋ณ์, ์์ ํ์ง ์์ ํจ์, ์ธ๋ถ ํจ์
Today, we will cover some more advanced topics of Rust:
- Traits: deriving traits, default methods, and important standard library traits.
- Generics: generic data types, generic methods, monomorphization, and trait objects.
- Error handling: panics,
Result
, and the try operator?
.- Testing: unit tests, documentation tests, and integration tests.
- Unsafe Rust: raw pointers, static variables, unsafe functions, and extern functions.
Traits
๋ฌ์คํธ๋ ์ธํฐํ์ด์ค ์ฒ๋ผ ํธ๋ ์ดํธ๊ฐ ์๋ ํ์ ์ ์ถ์ํ ํ ์ ์์ต๋๋ค:
Rust lets you abstract over types with traits. Theyโre similar to interfaces:
trait Greet { fn say_hello(&self); } struct Dog { name: String, } // name ์์. ๊ณ ์์ด๋ ์ด์จ๋ ๋ฐ์ํ์ง ์์ต๋๋ค... // No name, cats won't respond to it anyway. struct Cat; impl Greet for Dog { fn say_hello(&self) { println!("Wuf, my name is {}!", self.name); } } impl Greet for Cat { fn say_hello(&self) { println!("Miau!"); } } fn main() { let pets: Vec<Box<dyn Greet>> = vec![ Box::new(Dog { name: String::from("Fido") }), Box::new(Cat), ]; for pet in pets { pet.say_hello(); } }
Deriving Traits
์ปด์ฐจ์ผ๋ฌ๊ฐ ์ฌ๋ฌ๊ฐ์ง ํธ๋ ์ดํธ๋ฅผ ํ์(derive)ํ๋๋ก ํ ์ ์์ต๋๋ค:
You can let the compiler derive a number of traits:
#[derive(Debug, Clone, PartialEq, Eq, Default)] struct Player { name: String, strength: u8, hit_points: u8, } fn main() { let p1 = Player::default(); let p2 = p1.clone(); println!("Is {:?}\nequal to {:?}?\nThe answer is {}!", &p1, &p2, if p1 == p2 { "yes" } else { "no" }); }
Default Methods
ํธ๋ ์ดํธ๋ ๋ค๋ฅธ ํธ๋ ์ดํธ ๋ฉ์๋์์์ ๋์์ ๊ตฌํํ ์ ์์ต๋๋ค.
Traits can implement behavior in terms of other trait methods:
trait Equals { fn equal(&self, other: &Self) -> bool; fn not_equal(&self, other: &Self) -> bool { !self.equal(other) } } #[derive(Debug)] struct Centimeter(i16); impl Equals for Centimeter { fn equal(&self, other: &Centimeter) -> bool { self.0 == other.0 } } fn main() { let a = Centimeter(10); let b = Centimeter(20); println!("{a:?} equals {b:?}: {}", a.equal(&b)); println!("{a:?} not_equals {b:?}: {}", a.not_equal(&b)); }
์ญ์ฃผ
- Equals ํธ๋ ์ดํธ์์ equal์ ์ ์ธ๋ง ๋์ด์๊ณ not_equal์์ ์ด๋ฅผ ํธ์ถํ๊ณ ์์ต๋๋ค. (์ถ์ ๋ฉ์๋)
- impl์์ equal ๋ฉ์๋๋ฅผ ์ ์ํ๊ณ ์์ด์ Centimeter์์์ equal ๋ฉ์๋๋ฅผ ๊ตฌํ๋์ด ์์ต๋๋ค.(์ถ์ ๋ฉ์๋ ๊ตฌํ)
Important Traits
๋ฌ์คํธ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ์์ฃผ ์ฌ์ฉํ๋ ๋ช๊ฐ์ง ํธ๋ ์ดํธ ์์์ ๋๋ค:
Iterator
์IntoIterator
ํธ๋ ์ดํธ๋for
๋ฃจํ์์ ์ฌ์ฉ๋ฉ๋๋ค.From
๊ณผInto
ํธ๋ ์ดํธ๋ ํ์ ๋ณํ์ ์ฌ์ฉ๋ฉ๋๋ค.Read
์Write
ํธ๋ ์ดํธ๋ I/O์ ์ฌ์ฉ๋ฉ๋๋ค.Add
,Mul
๋ฑ์ ํธ๋ ์ดํธ๋ค์ ์ฐ์ฐ์ ์ค๋ฒ๋ก๋ฉ(overloading)์ ์ฌ์ฉ๋ฉ๋๋ค.Drop
ํธ๋ ์ดํธ๋ ์๋ฉธ์ ์ ์์ ์ฌ์ฉ๋ฉ๋๋ค.
We will now look at some of the most common traits of the Rust standard library:
Iterator
andIntoIterator
used infor
loops,From
andInto
used to convert values,Read
andWrite
used for IO,Add
,Mul
, โฆ used for operator overloading, andDrop
used for defining destructors.
Iterators
Iterator
๋ฅผ ์ปค์คํ
ํ์
์ ๊ตฌํํ ์ ์์ต๋๋ค:
You can implement the
Iterator
trait on your own types:
struct Fibonacci { curr: u32, next: u32, } impl Iterator for Fibonacci { type Item = u32; fn next(&mut self) -> Option<Self::Item> { let new_next = self.curr + self.next; self.curr = self.next; self.next = new_next; Some(self.curr) } } fn main() { let fib = Fibonacci { curr: 0, next: 1 }; for (i, n) in fib.enumerate().take(5) { println!("fib({i}): {n}"); } }
์ญ์ฃผ
- ์ดํฐ๋ ์ดํฐ ํธ๋ ์ดํธ์ next()๋ฅผ ์ค๋ฒ๋ก๋ฉํ ์์
From
and Into
ํ์
์ ์ฉ์ดํ ํ๋ณํ์ ์ํด From
๊ณผ Into
๋ฅผ ๊ตฌํํฉ๋๋ค:
Types implement
From
andInto
to facilitate type conversions:
fn main() { let s = String::from("hello"); let addr = std::net::Ipv4Addr::from([127, 0, 0, 1]); let one = i16::from(true); let bigger = i32::from(123i16); println!("{s}, {addr}, {one}, {bigger}"); }
From
์ด ๊ตฌํ๋๋ฉด Into
์ญ์ ์๋์ผ๋ก ๊ตฌํ๋ฉ๋๋ค:
Into
is automatically implemented whenFrom
is implemented:
fn main() { let s: String = "hello".into(); let addr: std::net::Ipv4Addr = [127, 0, 0, 1].into(); let one: i16 = true.into(); let bigger: i32 = 123i16.into(); println!("{s}, {addr}, {one}, {bigger}"); }
Read
and Write
Read
์ BufRead
๋ฅผ ์ฌ์ฉํ๋ฉด u8
์์ค๋ก๋ถํฐ ์ฝ์ ์ ์์ต๋๋ค:
Using
Read
andBufRead
, you can abstract overu8
sources:
use std::io::{BufRead, BufReader, Read, Result}; fn count_lines<R: Read>(reader: R) -> usize { let buf_reader = BufReader::new(reader); buf_reader.lines().count() } fn main() -> Result<()> { let slice: &[u8] = b"foo\nbar\nbaz\n"; println!("lines in slice: {}", count_lines(slice)); let file = std::fs::File::open(std::env::current_exe()?)?; println!("lines in file: {}", count_lines(file)); Ok(()) }
์ ์ฌํ๊ฒ Write
๋ฅผ ํตํด u8
์์ค๋ก ์ถ๋ ฅํ ์ ์์ต๋๋ค:
Similarly,
Write
lets you abstract overu8
sinks:
use std::io::{Result, Write}; fn log<W: Write>(writer: &mut W, msg: &str) -> Result<()> { writer.write_all(msg.as_bytes())?; writer.write_all("\n".as_bytes()) } fn main() -> Result<()> { let mut buffer = Vec::new(); log(&mut buffer, "Hello")?; log(&mut buffer, "World")?; println!("Logged: {:?}", buffer); Ok(()) }
Add
, Mul
, โฆ
์ฐ์ฐ์ ์ค๋ฒ๋ก๋๋ std::ops
ํธ๋ ์ดํธ์ ํตํด ๊ตฌํ๋ฉ๋๋ค:
Operator overloading is implemented via traits in
std::ops
:
#[derive(Debug, Copy, Clone)] struct Point { x: i32, y: i32 } // + ์ฐ์ฐ์ ์ค๋ฒ๋ก๋ฉ impl std::ops::Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Self {x: self.x + other.x, y: self.y + other.y} } } fn main() { let p1 = Point { x: 10, y: 20 }; let p2 = Point { x: 100, y: 200 }; println!("{:?} + {:?} = {:?}", p1, p2, p1 + p2); }
The Drop
Trait
Drop
ํธ๋ ์ดํธ๋ ๊ฐ์ด ์ค์ฝํ ๋ฐ์ผ๋ก ๋๊ฐ๋ ์คํํ๋ ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค:
Values which implement
Drop
can specify code to run when they go out of scope:
struct Droppable { name: &'static str, } impl Drop for Droppable { fn drop(&mut self) { println!("Dropping {}", self.name); } } fn main() { let a = Droppable { name: "a" }; { let b = Droppable { name: "b" }; { let c = Droppable { name: "c" }; let d = Droppable { name: "d" }; println!("Exiting block B"); } println!("Exiting block A"); } drop(a); println!("Exiting main"); }
Generics
๋ฌ์คํธ๋ ์ ๋๋ฆญ์ ์ง์ํ์ฌ ์ ๋ ฌ๊ณผ ๊ฐ์ ์๊ณ ๋ฆฌ์ฆ์ ์ ์ฉ๋๋ ํ์ ์ ์ถ์ํ ํ ์ ์์ต๋๋ค.
Rust support generics, which lets you abstract an algorithm (such as sorting) over the types used in the algorithm.
Generic Data Types
์ ๋๋ฆญ์ ์ฌ์ฉํ์ฌ ๊ตฌ์ฒด์ ์ธ ํ์ ์ ์ถ์ํํ ์ ์์ต๋๋ค:
You can use generics to abstract over the concrete field type:
#[derive(Debug)] struct Point<T> { x: T, y: T, } fn main() { let integer = Point { x: 5, y: 10 }; let float = Point { x: 1.0, y: 4.0 }; println!("{integer:?} and {float:?}"); }
Generic Methods
impl
๋ธ๋ก์์๋ ์ ๋๋ฆญ ํ์
์ ์ ์ธํ ์ ์์ต๋๋ค:
You can declare a generic type on your
impl
block:
#[derive(Debug)] struct Point<T>(T, T); impl<T> Point<T> { fn x(&self) -> &T { &self.0 // + 10 } // fn set_x(&mut self, x: T) } fn main() { let p = Point(5, 10); println!("p.x = {}", p.x()); }
Trait Bounds
T:
or impl
ํธ๋ ์ดํธ๋ฅผ ์ฌ์ฉํ์ฌ ์ ๋๋ฆญ์ ์ฌ์ฉํ ๋ ํ์
์ ์ ํํ ์ ์์ต๋๋ค:
When working with generics, you often want to limit the types. You can do this with
T: Trait
orimpl Trait
:
fn duplicate<T: Clone>(a: T) -> (T, T) { (a.clone(), a.clone()) } // struct NotClonable; fn main() { let foo = String::from("foo"); let pair = duplicate(foo); }
impl Trait
ํธ๋ ์ดํธ ๋ฐ์ด๋์ ์ ์ฌํ๊ฒ impl
ํธ๋ ์ดํธ ๋ฌธ๋ฒ์ ํจ์์ ์ธ์์ ๋ฐํ๊ฐ์ ์ ์ฉ ๊ฐ๋ฅํฉ๋๋ค:
Similar to trait bounds, an
impl Trait
syntax can be used in function arguments and return values:
use std::fmt::Display; fn get_x(name: impl Display) -> impl Display { format!("Hello {name}") } fn main() { let x = get_x("foo"); println!("{x}"); }
impl
ํธ๋ ์ดํธ๋ ํฐ๋ณดํผ์ฌ๋ฌธ๋ฒ(::<>
)์๋ ์ฌ์ฉํ ์ ์์ต๋๋ค.impl
ํธ๋ ์ดํธ๋ ์ต๋ช ํ์ ๊ณผ ์ฌ์ฉํ ์ ์์ต๋๋ค.
impl Trait
cannot be used with the::<>
turbo fish syntax.impl Trait
allows you to work with types which you cannot name.
Closures
ํด๋ก์ ํน์ ๋๋คํํ์์ ์ต๋ช
ํ์
์
๋๋ค. ์ด๋ค์
Fn
,
FnMut
,
FnOnce
๋ผ๋ ํน๋ณํ ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํฉ๋๋ค.
Closures or lambda expressions have types which cannot be named. However, they
implement special Fn
,
FnMut
, and
FnOnce
traits:
fn apply_with_log(func: impl FnOnce(i32) -> i32, input: i32) -> i32 { println!("Calling function on {input}"); func(input) } fn main() { let add_3 = |x| x + 3; let mul_5 = |x| x * 5; println!("add_3: {}", apply_with_log(add_3, 10)); println!("mul_5: {}", apply_with_log(mul_5, 20)); }
Monomorphization1
์ ๋๋ฆญ ์ฝ๋๋ ํธ์ถ๋ถ์์ ๋น ์ ๋๋ฆญ ์ฝ๋๋ก ์ ํ๋ฉ๋๋ค:
Generic code is turned into non-generic code based on the call sites:
fn main() { let integer = Some(5); let float = Some(5.0); }
์ ์ฝ๋๋ ์๋์ ๊ฐ์ด ๋์ํฉ๋๋ค.
behaves as if you wrote
enum Option_i32 { Some(i32), None, } enum Option_f64 { Some(f64), None, } fn main() { let integer = Option_i32::Some(5); let float = Option_f64::Some(5.0); }
์ด๊ฒ์ ์ฝ์คํธ๊ฐ ๋ค์ง ์๋ ์ถ์ํ1์ ๋๋ค: ์ถ์ํ ์์ด ์ง์ ์ฝ๋ฉํ ๊ฒ๊ณผ ์ ํํ ๊ฐ์ ๊ฒฐ๊ณผ์ ๋๋ค.
This is a zero-cost abstraction: you get exactly the same result as if you had hand-coded the data structures without the abstraction.
์ญ์ฃผ
์ ๋๋ฆญ๊ณผ ๊ฐ์ด ๋ฐํ์ ์ฝ์คํธ ์์ด ์ปดํ์ผ ์ฝ์คํธ๋ง์ผ๋ก ๋์ํ๋ ์ถ์ํ ์ปจ์ ์ ๋๋ค.
Trait Objects
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ ๋ ์ธ์๋ฅผ ์ทจํ๋ ๋ฐฉ๋ฒ:
Weโve seen how a function can take arguments which implement a trait:
use std::fmt::Display; fn print<T: Display>(x: T) { println!("Your value: {}", x); } fn main() { print(123); print("Hello"); }
์๋์ ๊ฐ์ด ์ฌ๋ฌ๊ฐ์ง ํ์ ์ ํผํฉํ์ฌ ์ธ์๋ก ๋ฐ๋ ค๋ฉด ์ด๋ป๊ฒ ํด์ผ ํฉ๋๊น?
However, how can we store a collection of mixed types which implement
Display
?
fn main() { let xs = vec![123, "Hello"]; }
์ด๋ฅผ ์ํด์ _ํธ๋ ์ดํธ ๊ฐ์ฒด_๊ฐ ํ์ํฉ๋๋ค:
For this, we need trait objects:
use std::fmt::Display; fn main() { let xs: Vec<Box<dyn Display>> = vec![Box::new(123), Box::new("Hello")]; for x in xs { println!("x: {x}"); } }
xs
๊ฐ ํ ๋น๋ ๋ ๋ฉ๋ชจ๋ฆฌ ๋ ์ด์์:
Memory layout after allocating
xs
:
๋ง์ฐฌ๊ฐ์ง๋ก ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํ ๋ค๋ฅธ ๊ฐ์ ๋ฐํํ ๋๋ ํธ๋ ์ดํธ ๊ฐ์ฒด๊ฐ ํ์ํฉ๋๋ค:
Similarly, you need a trait object if you want to return different values implementing a trait:
fn numbers(n: i32) -> Box<dyn Iterator<Item=i32>> { if n > 0 { Box::new(0..n) } else { Box::new((n..0).rev()) } } fn main() { println!("{:?}", numbers(-5).collect::<Vec<_>>()); println!("{:?}", numbers(5).collect::<Vec<_>>()); }
Day 3: Morning Exercises
์ด๋ฒ ์ฐ์ต๋ฌธ์ ์์๋ ํธ๋ ์ดํธ์ ํธ๋ ์ดํธ ๊ฐ์ฒด๋ฅผ ํตํด ๊ณ ์ ์ ์ธ GUI๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ค๊ณํ ๊ฒ์ ๋๋ค.
We will design a classical GUI library traits and trait objects.
A Simple GUI Library
ํธ๋ ์ดํธ์ ํธ๋ ์ดํธ ๊ฐ์ฒด ์ง์์ ํ์ฉํ์ฌ ๊ณ ์ ์ ์ธ GUI ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ค๊ณํฉ๋๋ค. ๋ผ์ด๋ธ๋ฌ๋ฆฌ์๋ ๋ช๊ฐ์ง ์์ ฏ์ด ์์ต๋๋ค:
Window
:title
์์ฑ๊ณผ ๋ค๋ฅธ ์์ ฏ์ด ํฌํจ๋ฉ๋๋ค.Button
:label
์์ ฏ๊ณผ ๋ฒํผ์ด ๋๋ ธ์๋ ์คํ๋๋ ์ฝ๋ฐฑ ํจ์๊ฐ ์์ต๋๋ค.Label
:label
์์ ฏ ์ ๋๋ค. ์์ ฏ์Widget
ํธ๋ ์ดํธ๋ฅผ ๊ตฌํํฉ๋๋ค. ์๋ ์ฝ๋๋ฅผ ์ฐธ์กฐํ์ธ์
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํ๊ณ ๋๋ฝ๋ draw_into
๋ฉ์๋๋ฅผ ์ฑ์ ๋ฃ์ด Widget
ํธ๋ ์ดํธ๋ฅผ ์์ฑํด๋ด
์๋ค:
Let us design a classical GUI library using our new knowledge of traits and trait objects. We will have a number of widgets in our library:
Window
: has atitle
and contains other widgets.Button
: has alabel
and a callback function which is invoked when the button is pressed.Label
: has alabel
.The widgets will implement a
Widget
trait, see below.
Copy the code below to https://play.rust-lang.org/, fill in the missingdraw_into
methods so that you implement theWidget
trait:
// TODO: remove this when you're done with your implementation. #![allow(unused_imports, unused_variables, dead_code)] pub trait Widget { /// Natural width of `self`. fn width(&self) -> usize; /// Draw the widget into a buffer. fn draw_into(&self, buffer: &mut dyn std::fmt::Write); /// Draw the widget on standard output. fn draw(&self) { let mut buffer = String::new(); self.draw_into(&mut buffer); println!("{}", &buffer); } } pub struct Label { label: String, } impl Label { fn new(label: &str) -> Label { Label { label: label.to_owned(), } } } pub struct Button { label: Label, callback: Box<dyn FnMut()>, } impl Button { fn new(label: &str, callback: Box<dyn FnMut()>) -> Button { Button { label: Label::new(label), callback, } } } pub struct Window { title: String, widgets: Vec<Box<dyn Widget>>, } impl Window { fn new(title: &str) -> Window { Window { title: title.to_owned(), widgets: Vec::new(), } } fn add_widget(&mut self, widget: Box<dyn Widget>) { self.widgets.push(widget); } } impl Widget for Label { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } impl Widget for Button { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } impl Widget for Window { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } fn main() { let mut window = Window::new("Rust GUI Demo 1.23"); window.add_widget(Box::new(Label::new("This is a small text GUI demo."))); window.add_widget(Box::new(Button::new( "Click me!", Box::new(|| println!("You clicked the button!")), ))); window.draw(); }
์ ํ๋ก๊ทธ๋จ์ ์ถ๋ ฅ์ ์๋์ ๊ฐ์ต๋๋ค:
The output of the above program can be something simple like this:
========
Rust GUI Demo 1.23
========
This is a small text GUI demo.
| Click me! |
์ ๋ ฅ๋ ๊ธ์๋ฅผ ๊ทธ๋ฆฌ๊ธฐ ์ํด์๋ fill/alignment ๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค. ํน์ ๋ฌธ์(์ฌ๊ธฐ์๋ โ/โ)๋ก ํจ๋ฉ์ ์ฃผ๋ ๋ฐฉ๋ฒ๊ณผ ์ ๋ ฌ์ ์ ์ดํ๋ ๋ฐฉ๋ฒ์ ํ์ธํ์๊ธฐ ๋ฐ๋๋๋ค.
If you want to draw aligned text, you can use the fill/alignment formatting operators. In particular, notice how you can pad with different characters (here a
'/'
) and how you can control alignment:
fn main() { let width = 10; println!("left aligned: |{:/<width$}|", "foo"); println!("centered: |{:/^width$}|", "foo"); println!("right aligned: |{:/>width$}|", "foo"); }
์์ ์ ๋ ฌ ํธ๋ฆญ์ ์ฌ์ฉํ์ฌ ๋ค์๊ณผ ๊ฐ์ ์ถ๋ ฅ์ ์์ฑํ ์ ์์ต๋๋ค.
Using such alignment tricks, you can for example produce output like this:
+--------------------------------+
| Rust GUI Demo 1.23 |
+================================+
| This is a small text GUI demo. |
| +-----------+ |
| | Click me! | |
| +-----------+ |
+--------------------------------+
์ญ์ฃผ
- ์ถ๊ฐ ๊ตฌํํ ํจ์๋ ์๊ณ
impl Widget for ~
์ ๋ ๋ฉ์๋๋ค๋ง ๊ตฌํํ๋ฉด ๋ฉ๋๋ค. - label์ ์ค๋ฐ๊ฟ(๊ฐํ)๋ฌธ์๋ ํฌํจ๋ ์ ์์ต๋๋ค.
\n
Error Handling
๋ฌ์คํธ์ ์ค๋ฅ ์ฒ๋ฆฌ๋ ๋ช ์์ ์ธ ํ๋ฆ์ ์ด๋ก ์ฒ๋ฆฌ๋ฉ๋๋ค:
- ์ค๋ฅ๋ฅผ ๋ฐ์ํ ์ ์๋ ํจ์๋ ๋ฐํ ํ์ ์ ๋ช ์ํฉ๋๋ค.
- ์์ธ๋ ์์ต๋๋ค.
Error handling in Rust is done using explicit control flow:
- Functions that can have errors list this in their return type,
- There are no exceptions.
Panics
๋ฌ์คํธ๋ ๋ฐํ์์์ ์น๋ช ์ ์ธ ์ค๋ฅ๋ฅผ ๋ง๋๋ฉด ํจ๋์ ๋ฐ์ํ ๊ฒ์ ๋๋ค:
Rust will trigger a panic if a fatal error happens at runtime:
fn main() { let v = vec![10, 20, 30]; println!("v[100]: {}", v[100]); }
- ํจ๋์ ๋ณต๊ตฌํ ์ ์๊ณ ์์์น ๋ชปํ ์ค๋ฅ์
๋๋ค.
- ํจ๋์ ํ๋ก๊ทธ๋จ ๋ฒ๊ทธ์ ์ฆ์์ ๋๋ค.
- ์ถฉ๋(ํฌ๋์)๋ฅผ ํ์ฉํ์ง ์์์ผ ํ๋ ๊ฒฝ์ฐ ํจ๋์ ์ ๋ฐํ์ง ์๋(non-panicking) API๋ฅผ ์ฌ์ฉํฉ๋๋ค.(
Vec::get
๋ฑ)
- Panics are for unrecoverable and unexpected errors.
- Panics are symptoms of bugs in the program.
- Use non-panicking APIs (such as
Vec::get
) if crashing is not acceptable.
์ญ์ฃผ
- ์ ์์ ์์ v[100]์ v.get(100) ์ผ๋ก ๋์ฒดํด๋ณด์ธ์
Catching the Stack Unwinding
๊ธฐ๋ณธ์ ์ผ๋ก, ํจ๋์ด ๋ฐ์ํ๋ฉด ์คํ์ ํด์ ๋ฉ๋๋ค. ์คํ ํด์ ๋ ๋ค์๊ณผ ๊ฐ์ด ์บ์น๊ฐ ๊ฐ๋ฅํฉ๋๋ค:
By default, a panic will cause the stack to unwind. The unwinding can be caught:
#![allow(unused)] fn main() { use std::panic; let result = panic::catch_unwind(|| { println!("hello!"); }); assert!(result.is_ok()); let result = panic::catch_unwind(|| { panic!("oh no!"); }); assert!(result.is_err()); }
- ์ด๊ฒ์ ๋จ์ผ ์์ฒญ์ด ํฌ๋์ ๋๋๋ผ๋ ๊ณ์ ์คํ๋์ผ ํ๋ ์๋ฒ์ ์ ์ฉํฉ๋๋ค.
Cargo.toml
์ค์ ํ์ผ์panic = abort
์ ์ค์ ํ๋ฉด ๋์ํ์ง ์์ต๋๋ค.
- This can be useful in servers which should keep running even if a single request crashes.
- This does not work if
panic = abort
is set in yourCargo.toml
.
Structured Error Handling with Result
Result
enum์ ํํ ์ค๋ฅ๋ฅผ ์์๋๋ ๊ฒฝ์ฐ ์ฌ์ฉ๋ฉ๋๋ค:
We have already seen the
Result
enum. This is used pervasively when errors are expected as part of normal operation:
use std::fs::File; use std::io::Read; fn main() { let file = File::open("diary.txt"); match file { Ok(mut file) => { let mut contents = String::new(); file.read_to_string(&mut contents); println!("Dear diary: {contents}"); }, Err(err) => { println!("The diary could not be opened: {err}"); } } }
Propagating Errors with ?
์๋(์ํ)์ฐ์ฐ์ ?
๋ ํธ์ถ์์๊ฒ ์ค๋ฅ๋ฅผ ๋ฐํํ ๋ ์ฌ์ฉํฉ๋๋ค.
The try-operator
?
is used to return errors to the caller. It lets you turn the common
match some_expression {
Ok(value) => value,
Err(err) => return Err(err),
}
ํจ์ฌ ๊ฐ๋จํ ๋ฐฉ์์ผ๋ก
into the much simpler
some_expression?
์ด๋ฅผ ์ฌ์ฉํ๋ฉด ์ค๋ฅ๋ฅผ ์ฒ๋ฆฌํ ์ ๋จ์ํ ํ ์ ์์ต๋๋ค:
We can use this to simplify our error handing code:
use std::fs; use std::io::{self, Read}; fn read_username(path: &str) -> Result<String, io::Error> { let username_file_result = fs::File::open(path); let mut username_file = match username_file_result { Ok(file) => file, Err(e) => return Err(e), }; let mut username = String::new(); match username_file.read_to_string(&mut username) { Ok(_) => Ok(username), Err(e) => Err(e), } } fn main() { //fs::write("config.dat", "alice").unwrap(); let username = read_username("config.dat"); println!("username: {username:?}"); }
Converting Error Types
?
์ ํจ๊ณผ์ ์ธ ์ ์ฉ์ ์ข ๋ ๋ณต์กํ๊ธด ํฉ๋๋ค:
The effective expansion of
?
is a little more complicated than previously indicated:
expression?
์ ํํ์ ์๋์ ๊ฐ์ต๋๋ค.
works the same as
match expression {
Ok(value) => value,
Err(err) => return Err(From::from(err)),
}
From::from
ํธ์ถ์ ์ค๋ฅํ์
์ ํจ์์์ ๋ฐํํ๋ ํ์
์ผ๋ก ๋ณํํฉ๋๋ค:
The
From::from
call here means we attempt to convert the error type to the type returned by the function:
use std::{fs, io}; use std::io::Read; #[derive(Debug)] enum ReadUsernameError { IoError(io::Error), EmptyUsername(String), } impl From<io::Error> for ReadUsernameError { fn from(err: io::Error) -> ReadUsernameError { ReadUsernameError::IoError(err) } } fn read_username(path: &str) -> Result<String, ReadUsernameError> { let mut username = String::with_capacity(100); fs::File::open(path)?.read_to_string(&mut username)?; if username.is_empty() { return Err(ReadUsernameError::EmptyUsername(String::from(path))); } Ok(username) } fn main() { //fs::write("config.dat", "").unwrap(); let username = read_username("config.dat"); println!("username: {username:?}"); }
Deriving Error Enums
thiserror ํฌ๋ ์ดํธ๋ ์ ํ์ด์ง์์ ์ฒ๋ผ ์ค๋ฅ enum์ ๋ง๋๋ ์ผ๋ฐ์ ์ธ ๋ฐฉ๋ฒ์ ๋๋ค.
The thiserror crate is a popular way to create an error enum like we did on the previous page:
use std::{fs, io}; use std::io::Read; use thiserror::Error; #[derive(Error, Debug)] enum ReadUsernameError { #[error("Could not read: {0}")] IoError(#[from] io::Error), #[error("Found no username in {0}")] EmptyUsername(String), } fn read_username(path: &str) -> Result<String, ReadUsernameError> { let mut username = String::with_capacity(100); fs::File::open(path)?.read_to_string(&mut username)?; if username.is_empty() { return Err(ReadUsernameError::EmptyUsername(String::from(path))); } Ok(username) } fn main() { //fs::write("config.dat", "").unwrap(); match read_username("config.dat") { Ok(username) => println!("Username: {username}"), Err(err) => println!("Error: {err}"), } }
Adding Context to Errors
anyhow ํฌ๋ ์ดํธ๋ ์ค๋ฅ์ ๋ํ ์ํฉ์ ๋ณด๋ฅผ ์ถ๊ฐํ๊ธฐ ์ํด ๋๋ฆฌ ์ฌ์ฉ๋๋ฉฐ ์ฌ์ฉ์ ์ ์ ์ค๋ฅ ์ ํ์ ์ค์ผ ์ ์์ต๋๋ค:
The widely used anyhow crate can help you add contextual information to your errors and allows you to have fewer custom error types:
use std::{fs, io}; use std::io::Read; use thiserror::Error; use anyhow::{Context, Result}; #[derive(Error, Debug)] enum ReadUsernameError { #[error("Found no username in {0}")] EmptyUsername(String), } fn read_username(path: &str) -> Result<String> { let mut username = String::with_capacity(100); fs::File::open(path) .context(format!("Failed to open {path}"))? .read_to_string(&mut username) .context("Failed to read")?; if username.is_empty() { return Err(ReadUsernameError::EmptyUsername(String::from(path)))?; } Ok(username) } fn main() { //fs::write("config.dat", "").unwrap(); match read_username("config.dat") { Ok(username) => println!("Username: {username}"), Err(err) => println!("Error: {err:?}"), } }
Testing
๋ฌ์คํธ์ ์นด๊ณ (cargo)๋ ๊ฐ๋จํ ํ ์คํธ ํ๋ ์์ํฌ์ ํจ๊ป ์ ๊ณต๋ฉ๋๋ค:
- ๋จ์ ํ ์คํธ๋ ์ฝ๋ ์ ๋ฐ์์ ์ง์๋ฉ๋๋ค.
- ํตํฉํ
์คํธ๋
test/
ํด๋๋ฅผ ํตํด ์ง์๋ฉ๋๋ค.
Rust and Cargo come with a simple unit test framework:
- Unit tests are supported throughout your code.
- Integration tests are supported via the
tests/
directory.
Unit Tests
๋จ์ ํ
์คํธ๋ #[test]
ํ๊ธฐ๋ก ์ด๋ค์ง๋๋ค:
Mark unit tests with
#[test]
:
fn first_word(text: &str) -> &str { match text.find(' ') { Some(idx) => &text[..idx], None => &text, } } #[test] fn test_empty() { assert_eq!(first_word(""), ""); } #[test] fn test_single_word() { assert_eq!(first_word("Hello"), "Hello"); } #[test] fn test_multiple_words() { assert_eq!(first_word("Hello World"), "Hello"); }
cargo test
์ปค๋งจ๋๋ฅผ ์ฌ์ฉํ๋ฉด ๋จ์ ํ
์คํธ๋ฅผ ์ฐพ์์ ์คํํฉ๋๋ค.
Use
cargo test
to find and run the unit tests.
Test Modules
๋จ์ ํ
์คํธ๋ ์ข
์ข
์ค์ฒฉ ๋ชจ๋ ์์ ์กด์ฌํฉ๋๋ค. ํ๋ ์ด๊ทธ๋ผ์ด๋์์ ์คํํ์๊ธฐ ๋ฐ๋๋๋ค)
โ> ๋จ์ ํ
์คํธ๋ ๋ชจ๋๋ก ๋ถ๋ฆฌํด์ ์ ์ธ ๊ฐ๋ฅํฉ๋๋ค.
Unit tests are often put in a nested module (run tests on the Playground)
fn helper(a: &str, b: &str) -> String { format!("{a} {b}") } pub fn main() { println!("{}", helper("Hello", "World")); } #[cfg(test)] mod tests { use super::*; #[test] fn test_helper() { assert_eq!(helper("foo", "bar"), "foo bar"); } }
- ๊ฐ๋ณํ๋ ํฌํผ๋ชจ๋์ ํตํด ๋จ์ํ ์คํธ๋ฅผ ์ํํ ์ ์์ต๋๋ค.
#[cfg(test)]
์์ฑ์ ์ค์งcargo test
์ปค๋งจ๋ ์คํ์ธ ๊ฒฝ์ฐ์๋ง ๋์ํฉ๋๋ค.
- This lets you unit test private helpers.
- The
#[cfg(test)]
attribute is only active when you runcargo test
.
Documentation Tests
๋ฌ์คํธ๋ ๋ฌธ์ํ ํ ์คํธ๋ฅผ ๋ด์ฅํ์ฌ ์ ๊ณตํฉ๋๋ค:
Rust has built-in support for documentation tests:
#![allow(unused)] fn main() { /// Shorten string will trip the string to the given length. /// /// ``` /// use playground::shorten_string; /// assert_eq!(shorten_string("Hello World", 5), "Hello"); /// assert_eq!(shorten_string("Hello World", 20), "Hello World"); /// ``` pub fn shorten_string(s: &str, length: usize) -> &str { &s[..std::cmp::min(length, s.len())] } }
///
์ฃผ์์ ์๋์ผ๋ก ๋ฌ์คํธ ์ฝ๋๋ก ํ์๋ฉ๋๋ค.- ์ด ์ฝ๋๋
cargo test
์ปค๋งจ๋ ๊ตฌ๋์ ์ปดํ์ผ๋๊ณ ์คํ๋ฉ๋๋ค. - ์ ์ฝ๋๋ฅผ ํ ์คํธ ํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค.Rust Playground.
- Code blocks in
///
comments are automatically seen as Rust code.- The code will be compiled and executed as part of
cargo test
.- Test the above code on the Rust Playground.
Integration Tests
๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ค์ ํ
์คํธ ํ๊ธฐ์ํ ํตํฉํ
์คํธ๋ test/
ํด๋ ๋ด์ .rs
๋ฅผ ์์ฑํ์ฌ ์ํํฉ๋๋ค:
If you want to test your library as a client, use an integration test. Create a
.rs
file undertests/
:
use my_library::init;
#[test]
fn test_init() {
assert!(init().is_ok());
}
์ด ํ ์คํธ๋ ํฌ๋ ์ดํธ์ ๊ณต๊ฐ API์๋ง ์ ๊ทผํ ์ ์์ต๋๋ค.
These tests only have access to the public API of your crate.
Unsafe Rust
๋ฌ์คํธ์ ๋ฌธ๋ฒ์ ํฌ๊ฒ ๋๊ฐ์ง ๋ถ๋ถ์ผ๋ก ๋๋ฉ๋๋ค:
- ์์ ํ ๋ฌ์คํธ: ์์ ํ ๋ฉ๋ชจ๋ฆฌ, ์ ์๋์ง ์์ ๋์ ๊ฐ๋ฅ์ฑ ์์.
- ์์ ํ์ง ์์ ๋ฌ์คํธ: ์ฌ์ ์กฐ๊ฑด์ ์๋ฐํ๋ ๊ฒฝ์ฐ ์ ์๋์ง ์์ ๋์์ ์ํํ ์ ์์ต๋๋ค.
์ด ๊ฐ์๋ ๋๋ถ๋ถ ์์ ํ ๋ฌ์คํธ์ ๋ํด ๋ค๋ฃจ์ง๋ง ์์ ํ์ง ์์ ๋ฌ์คํธ๊ฐ ๋ฌด์์ธ์ง ์์ ๋์ด์ผ ํฉ๋๋ค.
์์ ํ์ง ์์ ๋ฌ์คํธ๋ ๋ค์๊ณผ ๊ฐ์ 5๊ฐ์ง ์๋ก์ด ๊ธฐ๋ฅ์ ์ ๊ณตํฉ๋๋ค:
- ์์ํฌ์ธํธ ์ญ์ฐธ์กฐ
- ์ ์ ๊ฐ๋ณ๋ณ์ ์ ๊ทผ ๋ฐ ์์
union
ํ๋ ์ ๊ทผextern
ํจ์๋ฅผ ํฌํจํunsafe
ํจ์ ํธ์ถunsafe
ํธ๋ ์ดํธ ๊ตฌํ
์ ๊ธฐ๋ฅ์ ๋ํด ๊ฐ๋ตํ ์ดํด๋ณด๊ฒ ์ต๋๋ค. ์์ธํ ๋ด์ฉ์ Chapter 19.1 in the Rust Book ์ Rustonomicon๋ฅผ ์ฐธ์กฐํ์ธ์
The Rust language has two parts:
- Safe Rust: memory safe, no undefined behavior possible.
- Unsafe Rust: can trigger undefined behavior if preconditions are violated.
We will be seeing mostly safe Rust in this course, but itโs important to know what Unsafe Rust is.
Unsafe Rust gives you access to five new capabilities:
- Dereference raw pointers.
- Access or modify mutable static variables.
- Access
union
fields.- Call
unsafe
functions, includingextern
functions.- Implement
unsafe
traits.We will briefly cover these capabilities next. For full details, please see Chapter 19.1 in the Rust Book and the Rustonomicon.
Dereferencing Raw Pointers
ํฌ์ธํธ ์์ฑ์ ์์ ํฉ๋๋ค. ํ์ง๋ง ์ญ์ฐธ์กฐํ ๊ฒฝ์ฐ unsafe
๊ฐ ํ์ํฉ๋๋ค:
Creating pointers is safe, but dereferencing them requires
unsafe
:
fn main() { let mut num = 5; let r1 = &mut num as *mut i32; let r2 = &num as *const i32; unsafe { println!("r1 is: {}", *r1); // ๋ง์ฝ r1์ด ๋์ ์ฐ๊ธฐ๊ฐ ๋๋ฉด ๋ฐ์ดํฐ ๋ ์ด์ค๊ฐ ๋ฐ์ํฉ๋๋ค! *r1 = 10; // Data race if r1 is being written concurrently! println!("r2 is: {}", *r2); } }
Mutable Static Variables
๋ถ๋ณ ์ ์ ๋ณ์๋ฅผ ์ฝ๋ ๊ฒ์ โ์์ โํฉ๋๋ค:
It is safe to read an immutable static variable:
static HELLO_WORLD: &str = "Hello, world!"; fn main() { println!("name is: {}", HELLO_WORLD); }
ํ์ง๋ง, ๋ฐ์ดํฐ ๋ ์ด์ค๊ฐ ๋ฐ์ํ ์ ์์ผ๋ฏ๋ก ์ ์ ๊ฐ๋ณ๋ณ์๋ฅผ ์ฝ๊ณ ์ฐ๋ ๊ฒ์ โ์์ ํ์ง ์์ต๋๋คโ:
However, since data races can occur, it is unsafe to read and write mutable static variables:
static mut COUNTER: u32 = 0; fn add_to_counter(inc: u32) { // ๋ฐ์ดํฐ ๋ ์ด์ค ๊ฐ๋ฅ์ฑ ์์ unsafe { COUNTER += inc; } // Potential data race! } fn main() { add_to_counter(42); // ๋ฐ์ดํฐ ๋ ์ด์ค ๊ฐ๋ฅ์ฑ ์์ unsafe { println!("COUNTER: {}", COUNTER); } // Potential data race! }
Calling Unsafe Functions
๋ค์๊ณผ ๊ฐ์ ์ถ๊ฐ ์ ์ ์กฐ๊ฑด์ด ์๋ ๊ฒฝ์ฐ ํจ์๋ ๋ฉ์๋๋ unsafe
ํ์ํ ์ ์์ต๋๋ค:
A function or method can be marked
unsafe
if it has extra preconditions you must uphold:
fn main() { let emojis = "๐ปโ๐"; unsafe { // ์ธ๋ฑ์ค๊ฐ UTF-8 ์ํ์ค ๊ฒฝ๊ณ์ ์์ง ์์๊ฒฝ์ฐ ์ ์๋์ง ์์ ๋์์ ๋๋ค. // Undefined behavior if indices do not lie on UTF-8 sequence boundaries. println!("{}", emojis.get_unchecked(0..4)); println!("{}", emojis.get_unchecked(4..7)); println!("{}", emojis.get_unchecked(7..11)); } }
Calling External Code
๋ค๋ฅธ ์ธ์ด์ ํจ์๋ ๋ฌ์คํธ์ ๋ณด์ฆ์ ์๋ฐํ ์ ์์ต๋๋ค. ๋ฐ๋ผ์ ์ด๋ฅผ ํธ์ถํ๋ ๊ฒ์ โ์์ ํ์ง ์์ต๋๋คโ:
Functions from other languages might violate the guarantees of Rust. Calling them is thus unsafe:
extern "C" { fn abs(input: i32) -> i32; } fn main() { unsafe { // Abs๊ฐ ์ค๋์ํ๋ ๊ฒฝ์ฐ ์ ์๋์ง ์์ ๋์์ด ๋ฉ๋๋ค. // Undefined behavior if abs misbehaves. println!("Absolute value of -3 according to C: {}", abs(-3)); } }
Unions
์ ๋์จํ์ ์ ์ด๊ฑฐํ(enum)๊ณผ ๊ฐ์ง๋ง ์ง์ ํ์ฑ ํ๋๋ฅผ ์ถ์ฒํด์ผ ํฉ๋๋ค:
Unions are like enums, but you need to track the active field yourself:
#[repr(C)] union MyUnion { i: u8, b: bool, } fn main() { let u = MyUnion { i: 42 }; println!("int: {}", unsafe { u.i }); // b๋ ์ ์ ๋์ง ์์์ต๋๋ค! println!("bool: {}", unsafe { u.b }); // Undefined behavior! }
Day 3: Afternoon Exercises
์ด๋ฒ ์ฐ์ต๋ฌธ์ ์์๋ ํ์ผ ํด๋๋ฅผ ์์ ํ๊ฒ ์ฝ์ ์ ์๋ ๋ํผ๋ฅผ ๋ง๋ค์ด ๋ด ๋๋ค.
Let us build a safe wrapper for reading directory content!
Safe FFI Wrapper
๋ฌ์คํธ๋ _์ธ๋ถ ๊ธฐ๋ฅ ํธ์ถ(FFI)_์ ์ง์ํฉ๋๋ค.
์ด๋ฅผ ์ด์ฉํ์ฌ C์์ ์ฌ์ฉํ ํด๋ ๋ด ํ์ผ์ด๋ฆ์ ์ฝ์ด์ค๋ glibc
ํจ์๋ฅผ ๋ง๋ค ๊ฒ์
๋๋ค.
์๋ ๋ฆฌ๋ ์ค ๋ฉ๋ด์ผ ๋ฌธ์๋ค์ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค:
์๋ ์ฝ๋๋ฅผ https://play.rust-lang.org/์ ๋ณต์ฌํ๊ณ ๋น ์ง ํจ์์ ๋ฉ์๋๋ฅผ ์ฑ์๋ด ๋๋ค.
Rust has great support for calling functions through a foreign function interface (FFI). We will use this to build a safe wrapper the
glibc
functions you would use from C to read the filenames of a directory.You will want to consult the manual pages:
You will also want to browse the
std::ffi
module, particular forCStr
andCString
types which are used to hold NUL-terminated strings coming from C. The Nomicon also has a very useful chapter about FFI.Copy the code below to https://play.rust-lang.org/ and fill in the missing functions and methods:
// TODO: remove this when you're done with your implementation. #![allow(unused_imports, unused_variables, dead_code)] mod ffi { use std::os::raw::{c_char, c_int, c_long, c_ulong, c_ushort}; // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html. #[repr(C)] pub struct DIR { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-gnu. #[repr(C)] pub struct dirent { pub d_ino: c_long, pub d_off: c_ulong, pub d_reclen: c_ushort, pub d_type: c_char, pub d_name: [c_char; 256], } extern "C" { pub fn opendir(s: *const c_char) -> *mut DIR; pub fn readdir(s: *mut DIR) -> *const dirent; pub fn closedir(s: *mut DIR) -> c_int; } } use std::ffi::{CStr, CString, OsStr, OsString}; use std::os::unix::ffi::OsStrExt; #[derive(Debug)] struct DirectoryIterator { path: CString, dir: *mut ffi::DIR, } impl DirectoryIterator { fn new(path: &str) -> Result<DirectoryIterator, String> { // Call opendir and return a Ok value if that worked, // otherwise return Err with a message. unimplemented!() } } impl Iterator for DirectoryIterator { type Item = OsString; fn next(&mut self) -> Option<OsString> { // Keep calling readdir until we get a NULL pointer back. unimplemented!() } } impl Drop for DirectoryIterator { fn drop(&mut self) { // Call closedir as needed. unimplemented!() } } fn main() -> Result<(), String> { let iter = DirectoryIterator::new(".")?; println!("files: {:#?}", iter.collect::<Vec<_>>()); Ok(()) }
์ญ์ฃผ
- DirectoryIterator, Iterator, Drop impl ๋ธ๋ก์ ์ฑ์ฐ๋ฉด ๋ฉ๋๋ค.
- ์ฐธ์กฐ๋ฌธ์๋ฅผ ์น ํ์ด๋ ์ด๋ ค์ด๋ฐ(โฆ)
Welcome to Day 4
์ค๋ ๊ฐ์๋ ๋๊ฐ์ง ์ฃผ์ ๋ฅผ ๋ค๋ฃน๋๋ค:
- ๋์์ฑ: ์ฐ๋ ๋, ์ฑ๋, ์ํ ๊ณต์ (์์ด ์คํ
์ดํธ),
Send
์Sync
- ์๋๋ก์ด๋: ๋ฐ์ด๋๋ฆฌ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์์ฑ, AIDL ์ฌ์ฉ, ๋ก๊น ๊ณผ C/C++, ์๋ฐ์์ ์ํธ ์ด์ฉ์ฑ
์ฐ๋ฆฌ๋ ์ค๋ ๋น์ ์ ํ๋ก์ ํธ๋ฅผ ํธ์ถํด๋ณผ ๊ฒ์ ๋๋ค. ๋ฐ๋ผ์ ๊ฐ์ง๊ณ ์๋ ์ฝ๋ ์ค์ ์์ ๋ถ๋ถ์ ์ฐพ์๋ณด์ธ์ ์ข ์์ฑ์ด ์ ๊ณ ํน์ด ํ์ ์ด ์ ์ ์๋ก ์ข์ต๋๋ค. raw byte๋ฅผ ๋ถ์ํ๋ ์ข ๋ฅ์ ๊ฒ์ด ์ด์์ ์ ๋๋ค.
Today we will look at two main topics:
Concurrency: threads, channels, shared state,
Send
andSync
.Android: building binaries and libraries, using AIDL, logging, and interoperability with C, C++, and Java.
We will attempt to call Rust from one of your own projects today. So try to find a little corner of your code base where we can move some lines of code to Rust. The fewer dependencies and โexoticโ types the better. Something that parses some raw bytes would be ideal.
Fearless Concurrency
๋ฌ์คํธ๋ ๋ฎคํ ์ค์ ์ฑ๋์ด ์๋ OS ์ค๋ ๋๋ฅผ ์ฌ์ฉํ์ฌ ๋์์ฑ์ ์์ ํ ์ง์ํฉ๋๋ค. ๋ฌ์คํธ์ ํ์ ์์คํ ์ ๋ง์ ๋์์ฑ ๋ฒ๊ทธ๊ฐ ์ปดํ์ผ ์ ๋ฒ๊ทธ๋ฅผ ์ผ์ผํค๋ ์ค์ํ ์ญํ ์ ํฉ๋๋ค. ์ด๋ ์ปดํ์ผ๋ฌ๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐํ์์ ์ ํ์ฑ์ ๋ณด์ฅํ ์ ์๊ธฐ ๋๋ฌธ์ ์ข ์ข _๊ฒ์๋ ๋์์ฑ(fearless concurrency)_๋ผ๊ณ ํฉ๋๋ค.
Rust has full support for concurrency using OS threads with mutexes an๊ฒ channels.
The Rust type system plays an important role in making many concurrency bugs compile time bugs. This is often referred to as fearless concurrency since you can rely on the compiler to ensure correctness at runtime.
์ญ์ฃผ
- ๋๋ฒ์งธ ๋ฌธ์ฅ์ด ๋ฏธ๋ฌํ๋ฐ ๋ฐํ์์ด ์๋๋ผ ์ปดํ์ผ์ ์ฒดํฌ๋ ์ ์๊ฒ ํด์ค์ (๋ฐํ์์)์ ํ์ฑ์ ๋ณด์ฅํด์ค๋ค๋ก ์ดํด๋ฉ๋๋ค.
Threads
๋ฌ์คํธ์ ์ค๋ ๋๋ ๋ค๋ฅธ ์ธ์ด์ ์ค๋ ๋์ ์ ์ฌํ๊ฒ ๋์ํฉ๋๋ค:
Rust threads work similarly to threads in other languages:
use std::thread; use std::time::Duration; fn main() { thread::spawn(|| { for i in 1..10 { println!("Count in thread: {i}!"); thread::sleep(Duration::from_millis(5)); } }); for i in 1..5 { println!("Main thread: {i}"); thread::sleep(Duration::from_millis(5)); } }
- ์ค๋ ๋๋ ๋ชจ๋ ๋ฐ๋ชฌ ์ค๋ ๋1์ ๋๋ค. ๋ฐ๋ผ์ ์ฃผ ์ค๋ ๋๋ ์ด๋ฅผ ๊ธฐ๋ค๋ฆฌ์ง ์์ต๋๋ค.
- ์ค๋ ๋์ ํจ๋์ ์๋ก ๋
๋ฆฝ์ ์ผ๋ก ๋ฐ์ํฉ๋๋ค.
- (์ค๋ ๋์) ํจ๋์ (์ฃผ ์ค๋ ๋์๊ฒ) ํ์ด๋ก๋๋ฅผ ์ ๋ฌํ๊ณ , ์ด๋
downcast_ref
๋ก ํ์ด๋ณผ ์ ์์ต๋๋ค.
- (์ค๋ ๋์) ํจ๋์ (์ฃผ ์ค๋ ๋์๊ฒ) ํ์ด๋ก๋๋ฅผ ์ ๋ฌํ๊ณ , ์ด๋
- Threads are all daemon threads, the main thread does not wait for them.
- Thread panics are independent of each other.
- Panics can carry a payload, which can be unpacked with
downcast_ref
.
๊ฐ์ ์ฐธ์กฐ ๋ ธํธ
ํคํฌ์ธํธ:
- ์ฃผ ์ค๋ ๋๊ฐ ๊ธฐ๋ค๋ฆฌ์ง ์๊ธฐ ๋๋ฌธ์ ์์ฑ๋ ์ค๋ ๋์ for๋ฌธ์ 10๊น์ง ๊ฐ์ง ์์ต๋๋ค.
- ๋ง์ฝ ์ฃผ ์ค๋ ๋๊ฐ ์ค๋ ๋ ๋์์ ๋๊ธฐ ํ๊ธฐ ์ํ๋ค๋ฉด
let handle = thread::spawn(...)
์ผ๋ก ์ค๋ ๋๋ฅผ ์ ์ธํ ํhandle.join()
๋ก ์ฐ๊ฒฐํ์ฌ ์ฌ์ฉํฉ๋๋ค. - ์ค๋ ๋์์ ์ ๋ฐ๋ ํจ๋(for ๊ฐ์ ์ข ๋ฃ)์ด ์ฃผ ์ค๋ ๋์๋ ์ํฅ์ด ์์์ ํ์ธํ์๊ธฐ ๋ฐ๋๋๋ค.
handle.join()
์ฌ์ฉ์Result
๋ฐํ๊ฐ์ ํตํด ํจ๋ ํ์ด๋ก๋์ ์ ๊ทผํ ์ ์์ต๋๋ค.Any
๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
Key points:
Notice that the thread is stopped before it reaches 10 โ the main thread is not waiting.
Use
let handle = thread::spawn(...)
and laterhandle.join()
to wait for the thread to finish.Trigger a panic in the thread, notice how this doesnโt affect
main
.Use the
Result
return value fromhandle.join()
to get access to the panic payload. This is a good time to talk aboutAny
.
์ญ์ฃผ
- ๋ค๋ฅธ์ธ์ด์ ์ค๋ ๋ === js๋ง ํ์ผ๋ฉด ํฌ๊ฒ์ดํธ ์ด๋ฆฌ๋ ์ฅ์ ๋๋ค(โฆ)
๋ฐ๋ชฌ ์ค๋ ๋๋ ์ผ๋ฐ ์ค๋ ๋์ ๋ณด์กฐ ์ค๋ ๋๋ก ์ฃผ ์ค๋ ๋๊ฐ ์ข ๋ฃ๋๋ฉด ๊ฐ์ด ์ข ๋ฃ๋๊ณ , ๋ฐฑ๊ทธ๋ผ์ด๋์์ ๋ฎ์ ์ฐ์ ์์๋ก ๋์ํฉ๋๋ค.
- ๋ฐ๋ชฌ: ์ฌ์ฉ์๊ฐ ์ง์ ์ ์ผ๋ก ์ ์ดํ์ง ์๊ณ ๋ฐฑ๊ทธ๋ผ์ด๋์์ ๋์ํ๋ ํ๋ก๊ทธ๋จ.
Scoped Threads
์ผ๋ฐ ์ค๋ ๋๋ ๊ทธ๋ค์ ํ๊ฒฝ(์ฃผ ์ค๋ ๋)์์ ๋น๋ฆด์ ์์ต๋๋ค:
Normal threads cannot borrow from their environment:
use std::thread; fn main() { let s = String::from("Hello"); thread::spawn(|| { println!("Length: {}", s.len()); }); }
ํ์ง๋ง, scoped thread์์๋ ๊ฐ๋ฅํฉ๋๋ค: However, you can use a scoped thread for this:
use std::thread; fn main() { let s = String::from("Hello"); thread::scope(|scope| { scope.spawn(|| { println!("Length: {}", s.len()); }); }); }
Channels
๋ฌ์คํธ์ ์ฑ๋์ Sender์
Receiver
Rust channels have two parts: a
Sender<T>
and aReceiver<T>
. The two parts are connected via the channel, but you only see the end-points.
use std::sync::mpsc; use std::thread; fn main() { let (tx, rx) = mpsc::channel(); tx.send(10).unwrap(); tx.send(20).unwrap(); println!("Received: {:?}", rx.recv()); println!("Received: {:?}", rx.recv()); let tx2 = tx.clone(); tx2.send(30).unwrap(); println!("Received: {:?}", rx.recv()); }
์ญ์ฃผ
- ๋ฉ์ธ์ง ํจ์ฑํ๋ transmitter(tx)์ receiver(rx) ์ ๋๋ค. ๋ณดํต ์์๋ ํ๋ฅด๋ ๊ฐ์ธ(์ฑ๋) ์๋ฅ(tx)์ ๋์ด ๊ณ ๋ฌด ์ค๋ฆฌ๊ฐ ํ๋ฅ(rx)๋ก ๊ฐ๋ ํ๋ฆ์ ์๊ฐํ์๋ฉด ๋ฉ๋๋ค.
Unbounded Channels
mpsc::channel()
ํจ์๋ ๋ฌด์ ํ, ๋น๋๊ธฐ ์ฑ๋์ ์์ฑํฉ๋๋ค:
You get an unbounded and asynchronous channel with
mpsc::channel()
:
use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let thread_id = thread::current().id(); for i in 1..10 { tx.send(format!("Message {i}")).unwrap(); println!("{thread_id:?}: sent Message {i}"); } println!("{thread_id:?}: done"); }); thread::sleep(Duration::from_millis(100)); for msg in rx.iter() { println!("Main: got {}", msg); } }
Bounded Channels
๊ฒฝ๊ณ๊ฐ ์๋ ๋๊ธฐ ์ฑ๋์ send
๊ฐ ์ฃผ ์ค๋ ๋๋ฅผ ์ฐจ๋จํ๋๋ก ๋ง๋ญ๋๋ค:
Bounded and synchronous channels make
send
block the current thread:
use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { let (tx, rx) = mpsc::sync_channel(3); thread::spawn(move || { let thread_id = thread::current().id(); for i in 1..10 { tx.send(format!("Message {i}")).unwrap(); println!("{thread_id:?}: sent Message {i}"); } println!("{thread_id:?}: done"); }); thread::sleep(Duration::from_millis(100)); for msg in rx.iter() { println!("Main: got {}", msg); } }
Shared State
๋ฌ์คํธ๋ ์ฃผ๋ก ์๋ ๋ ๊ฐ์ง ํ์ ์์คํ ์ ์ด์ฉํด์ ๊ณต์ ๋ฐ์ดํฐ ๋๊ธฐํ๋ฅผ ์ํํฉ๋๋ค:
Rust uses the type system to enforce synchronization of shared data. This is primarily done via two types:
Arc<T>
, atomic1 ์ฐธ์กฐ ์นด์ดํธT
: ์ค๋ ๋ ์ฌ์ด์ ๊ณต์ ๋ฅผ ๋ด๋นํ๊ณ , ๋ง์ง๋ง ์ค๋ ๋ ์ข ๋ฃ์ T๋ฅผ ํด์ ํฉ๋๋ค.Mutex<T>
:T
๊ฐ์ ๋ํ ์ํธ๋ฐฐ์ ์์ธ์ค๋ฅผ ๋ณด์ฅํฉ๋๋ค.
์ญ์ฃผ
C++์ atomic์ ๊ตฌํํ๋ค๊ณ ํฉ๋๋ค. ์์์ ์ฐ์ฐ(ํ๋ฒ์ ์ผ์ด๋๋ ๋ช ๋ น์ด ์ฐ์ฐ)์ผ๋ก 1๊ฐ์ ๋ช ๋ น์ด๋ก ์ฒ๋ฆฌํ๋ค/์ํ๋ค๋ก๋ง ์กด์ฌํฉ๋๋ค.
Arc
Arc<T>
๋ clone
๋ฉ์๋๋ฅผ ํตํด ์ฝ๊ธฐ์ ์ฉ ์ ๊ทผ์ ํ์ฉํฉ๋๋ค:
Arc<T>
allows shared read-only access via itsclone
method:
use std::thread; use std::sync::Arc; fn main() { let v = Arc::new(vec![10, 20, 30]); let mut handles = Vec::new(); for _ in 1..5 { let v = v.clone(); handles.push(thread::spawn(move || { let thread_id = thread::current().id(); println!("{thread_id:?}: {v:?}"); })); } handles.into_iter().for_each(|h| h.join().unwrap()); println!("v: {v:?}"); }
Mutex
Mutex<T>
๋ ์ํธ๋ฐฐ์ ๋ฅผ ๋ณด์ฅํ๊ณ , ์ผ๊ธฐ์ ์ฉ ์ธํฐํ์ด์ค ๋ค์์ T
์ ๋ํ ๊ฐ๋ณ ์ ๊ทผ์ ํ์ฉํฉ๋๋ค:
Mutex<T>
ensures mutual exclusion and allows mutable access toT
behind a read-only interface:
use std::sync::Mutex; fn main() { let v: Mutex<Vec<i32>> = Mutex::new(vec![10, 20, 30]); println!("v: {:?}", v.lock().unwrap()); { let v: &Mutex<Vec<i32>> = &v; let mut guard = v.lock().unwrap(); guard.push(40); } println!("v: {:?}", v.lock().unwrap()); }
impl<T: Send> Sync for Mutex<T>
๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค
Notice how we have a
impl<T: Send> Sync for Mutex<T>
blanket implementation.
Example
Arc
์ Mutex
์ ๋์์ ์ดํด๋ด
๋๋ค:
Let us see
Arc
andMutex
in action:
use std::thread; // use std::sync::{Arc, Mutex}; fn main() { let mut v = vec![10, 20, 30]; let handle = thread::spawn(|| { v.push(10); }); v.push(1000); handle.join().unwrap(); println!("v: {v:?}"); }
์ญ์ฃผ
- ์ ์ฝ๋๋ฅผ ๋์ํ๊ฒ ์์ ํด๋ณด์ธ์.
Send
and Sync
๋ฌ์คํธ๋ ์๋ ๋๊ฐ์ง ํธ๋ ์ดํธ๋ฅผ ์ด์ฉํ์ฌ ์ค๋ ๋ ๊ฐ ๊ณต์ ์ ๊ทผ์ ๊ธ์ง๋ ๊ฒ์ ์ ์ ์์ต๋๋ค:
Send
:T
๊ฐ ์ค๋ ๋ ๊ฐ ์ด๋์ด ์์ ํ๋ค๋ฉด,T
์ ํ์ ์Send
์ ๋๋ค.Sync
:&T
๊ฐ ์ค๋ ๋ ๊ฐ ์ด๋์ด ์์ ํ๋ค๋ฉด,&T
์ ํ์ ์Sync
์ ๋๋ค.
How does Rust know to forbid shared access across thread? The answer is in two traits:
Send
T
๊ฐ ์ค๋ ๋ ๊ฐ ์ด๋์ด ์์ ํ๋ค๋ฉด,T
์ ํ์ ์Send
์ ๋๋ค.A type
T
isSend
if it is safe to move aT
value to another thread.
์์ ๊ถ์ ๋ค๋ฅธ ์ค๋ ๋๋ก ์ด๋ํ๋ฉด ์๋ฉธ์๊ฐ ํด๋น ์ค๋ ๋์์ ์คํ๋ฉ๋๋ค.
์ฌ๊ธฐ์ ์๋ฌธ์ ์ธ์ ํ ์ค๋ ๋์์ ๊ฐ์ ํ ๋นํ๊ณ ๋ค๋ฅธ ์ค๋ ๋์์ ๊ฐ์ ํ ๋น ํด์ ํ ์ ์๋๊ฐ ์ ๋๋ค.
The effect of moving ownership to another thread is that destructors will run in that thread. So the question is when you can allocate a value in one thread and deallocate it in another.
Sync
&T
๊ฐ ์ฌ๋ฌ ์ค๋ ๋์์ ์ ๊ทผ์ด ์์ ํ๋ค๋ฉด,&T
์ ํ์ ์Sync
์ ๋๋ค.A type
T
isSync
if it is safe to access aT
value from multiple threads at the same time.
์ข ๋ ์ ํํ ์ ์๋ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:
More precisely, the definition is:
&T
๋ง Send
์ธ ๊ฒฝ์ฐ, T
์ ํ์
์ Sync
์
๋๋ค.
T
isSync
if and only if&T
isSend
Examples
Send + Sync
๋๋ถ๋ถ์ ํ์
์ Send + Sync
์
๋๋ค:
i8
,f32
,bool
,char
,&str
, โฆ(T1, T2)
,[T; N]
,&[T]
,struct { x: T }
, โฆString
,Option<T>
,Vec<T>
,Box<T>
, โฆArc<T>
: atomic ์ฐธ์กฐ ์นด์ดํธ๋ก ๋ช ์์ ์ค๋ ๋-์ธ์ดํ.Mutex<T>
: ๋ด๋ถ ์ ๊ธ์ ํตํด ๋ช ์์ ์ค๋ ๋-์ธ์ดํ.AtomicBool
,AtomicU8
, โฆ: ํน๋ณํ atomic ๋ช ๋ น์ ์ฌ์ฉํฉ๋๋ค.
Most types you come across are
Send + Sync
:
i8
,f32
,bool
,char
,&str
, โฆ(T1, T2)
,[T; N]
,&[T]
,struct { x: T }
, โฆString
,Option<T>
,Vec<T>
,Box<T>
, โฆArc<T>
: Explicitly thread-safe via atomic reference count.Mutex<T>
: Explicitly thread-safe via internal locking.AtomicBool
,AtomicU8
, โฆ: Uses special atomic instructions.
์ ๋๋ฆญ ํ์
์ ์ผ๋ฐ์ ์ผ๋ก ํ์
ํ๋ผ๋ฉํฐ๊ฐ Send + Sync
์ด๋ฉด Send + Sync
์
๋๋ค.
The generic types are typically
Send + Sync
when the type parameters areSend + Sync
.
Send + !Sync
์๋ ํ์ ๋ค์ ์ผ๋ฐ์ ์ผ๋ก ๋ด๋ถ ๊ฐ๋ณ์ฑ์ผ๋ก ์ธํด ๋ค๋ฅธ ์ค๋ ๋๋ก ์ด๋๋ ์ ์์ง๋ง ์ค๋ ๋-์ธ์ดํ ํ์ง ์์ต๋๋ค.
These types can be moved to other threads, but theyโre not thread-safe. Typically because of interior mutability:
mpsc::Sender<T>
mpsc::Receiver<T>
Cell<T>
RefCell<T>
!Send + Sync
์๋ ํ์ ๋ค์ ์ค๋ ๋-์ธ์ดํ ํ์ง๋ง ๋ค๋ฅธ ์ค๋ ๋๋ก ์ด๋๋ ์ ์์ต๋๋ค:
MutexGuard<T>
: OS๋ ๋ฒจ์์ ์์ฑํ ์ค๋ ๋์์ ํ ๋นํด์ ํด์ผํฉ๋๋ค
These types are thread-safe, but they cannot be moved to another thread:
MutexGuard<T>
: Uses OS level primitives which must be deallocated on the thread which created them.
!Send + !Sync
์๋ ํ์ ๋ค์ ์ค๋ ๋-์ธ์ดํ ํ์ง๋ ์๊ณ ๋ค๋ฅธ ์ค๋ ๋๋ก ์ด๋๋ ์๋ ์์ต๋๋ค:
Rc<T>
: ๊ฐRc<T>
๋ ๋น atomic ์ฐธ์กฐ ์นด์ดํธ๋ฅผ ํฌํจํ๋RcBox<T>
๋ฅผ ์ฐธ์กฐํฉ๋๋ค.*const T
,*mut T
: ๋ฌ์คํธ๋ raw ํฌ์ธํฐ๊ฐ ํน๋ณํ ๋์์ฑ ๊ณ ๋ ค์ฌํญ์ ๊ฐ์ง ์ ์๋ค๊ณ ๊ฐ์ ํฉ๋๋ค.
These types are not thread-safe and cannot be moved to other threads:
Rc<T>
: eachRc<T>
has a reference to anRcBox<T>
, which contains a non-atomic reference count.*const T
,*mut T
: Rust assumes raw pointers may have special concurrency considerations.
Exercises
์ด๋ฒ ํ๋ จ์์๋ ๋์์ฑ ๊ธฐ์ ์ ์ฐ์ตํฉ๋๋ค:
- ์์ฌํ๋ ์ฒ ํ์ ๋ฌธ์ : ๊ณ ์ ์ ์ธ ๋์์ฑ ๋ฌธ์ ์ ๋๋ค.
- ๋ฉํฐ ์ค๋ ๋ ๋งํฌ ๊ฒ์ฌ: ์นด๊ณ ๋ฅผ ์ฌ์ฉํ์ฌ ์ข ์์ฑ์ ๋ค์ด๋ก๋ํ๋ฉด์ ๋งํฌ๋ฅผ ์ฒดํฌํ๋ ํฐ ํ๋ก์ ํธ์ ๋๋ค
Let us practice our new concurrency skills with
Dining philosophers: a classic problem in concurrency.
Multi-threaded link checker: a larger project where youโll use Cargo to download dependencies and then check links in parallel.
Dining Philosophers
์์ฌํ๋ ์ฒ ํ์ ๋ฌธ์ ๋ ๋์์ฑ์ ์์ด์ ๊ณ ์ ์ ์ธ ๋ฌธ์ ์ ๋๋ค:
5๋ช ์ ์ฒ ํ์๊ฐ ์ํ์์ ์์ฌ๋ฅผ ํ๊ณ ์์ต๋๋ค. ์ฒ ํ์๋ ์ํ์์ ์์ ์ ์๋ฆฌ์ ์์์์ต๋๋ค. ํฌํฌ๋ ๊ฐ ์ ์ ์ฌ์ด์ ์์ต๋๋ค. ์ ๊ณต๋๋ ์๋ฆฌ๋ฅผ ๋จน๊ธฐ ์ํด์๋ 2๊ฐ์ ํฌํฌ๋ฅผ ๋ชจ๋ ์ฌ์ฉํด์ผํฉ๋๋ค. ์ฒ ํ์๋ ์๊ฐ์ ํ๋ค๊ฐ ๋ฐฐ๊ฐ ๊ณ ํ๋ฉด ์์ ์ ์ข์ฐ์ ํฌํฌ๋ฅผ ๋ค์ด ์๋ฆฌ๋ฅผ ๋จน์ต๋๋ค. ์ฒ ํ์๋ ์๋ฆฌ๋ฅผ ๋จน์ ํ์๋ ํฌํฌ๋ฅผ ๋ค์ ์๋ฆฌ์ ๋ด๋ ค๋์ต๋๋ค. ์ฒ ํ์๋ ์์ ์ ์ข,์ฐ์ ํฌํฌ๊ฐ ์์๋๋ง ์๋ฆฌ๋ฅผ ๋จน์ ์ ์์ต๋๋ค. ๋ฐ๋ผ์ ๋๊ฐ์ ํฌํฌ๋ ์ค์ง ์์ ์ ์ข,์ฐ ์ฒ ํ์๊ฐ ์๊ฐ์ ํ ๋๋ง ์ฌ์ฉํ ์ ์์ต๋๋ค.
์ด๋ฒ ํ๋ จ์์๋ ๋ก์ปฌ ์นด๊ณ ์ค์น๊ฐ ํ์ํฉ๋๋ค.
์๋ ์ฝ๋๋ฅผ ๋ณต์ฌํด์ src/main.rs
์ ๋ถ์ฌ๋๊ณ ๋น ๋ถ๋ถ์ ์ฑ์ฐ๊ณ , cargo run
์ปค๋งจ๋๋ก ํ
์คํธ ํด์ ๊ต์ฐฉ์ํ(๋ฐ๋๋ฝ)์ด ๋์ง ์๋์ง ํ์ธํฉ๋๋ค:
The dining philosophers problem is a classic problem in concurrency:
Five philosophers dine together at the same table. Each philosopher has their own place at the table. There is a fork between each plate. The dish served is a kind of spaghetti which has to be eaten with two forks. Each philosopher can only alternately think and eat. Moreover, a philosopher can only eat their spaghetti when they have both a left and right fork. Thus two forks will only be available when their two nearest neighbors are thinking, not eating. After an individual philosopher finishes eating, they will put down both forks.
You will need a local Cargo installation for this exercise. Copy the code below to
src/main.rs
file, fill out the blanks, and test thatcargo run
does not deadlock:
use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; struct Fork; struct Philosopher { name: String, // left_fork: ... // right_fork: ... // thoughts: ... } impl Philosopher { fn think(&self) { self.thoughts .send(format!("Eureka! {} has a new idea!", &self.name)) .unwrap(); } fn eat(&self) { // Pick up forks... println!("{} is eating...", &self.name); thread::sleep(Duration::from_millis(10)); } } static PHILOSOPHERS: &[&str] = &["Socrates", "Plato", "Aristotle", "Thales", "Pythagoras"]; fn main() { // Create forks // Create philosophers // Make them think and eat // Output their thoughts }
์ญ์ฃผ
- ๋ก์ปฌ์์
cargo new dining-philosopher
๋ก ํ๋ก์ ํธ๋ฅผ ์์ฑํด์ ์ ์ฝ๋ ๋ถ์ฌ๋ฃ๊ณ ์์ํ๋ฉด ๋ฉ๋๋ค. - ๋ฐ๋๋ฝ ํํผ ์๊ณ ๋ฆฌ์ฆ ์์ฒด๋ฅผ ํ
์คํธ ํ๋๊ฑด ์๋๋ ๊ตฌ๊ธ ์์นญ go.
- ์ญ์๋ ์์น์ ๋ฐ๋ผ(ํ์ง) ๋๋ ํฌํฌ ์์๋ฅผ ๋ฐ๊พธ๋ ๋ฐฉ์์ผ๋ก ํ์ต๋๋ค.
Multi-threaded Link Checker
์๋ก ๋ฐฐ์ด๊ฒ๋ค์ ํ์ฉํด์ ๋ฉํฐ ์ค๋ ๋ ๋งํฌ ๊ฒ์ฌ๊ธฐ๋ฅผ ๋ง๋ญ๋๋ค. ๊ฒ์ฌ๊ธฐ๋ ์นํ์ด์ง๊ฐ ์ ํจํ์ง ํ์ธํฉ๋๋ค. ๊ทธ๋ฆฌ๊ณ ์ฌ๊ท์ ์ผ๋ก ๋์ผ ๋๋ฉ์ธ์ ๋ค๋ฅธ ๋ชจ๋ ํ์ด์ง๊ฐ ์ ํจํ์ง ํ์ธํฉ๋๋ค.
์ด๋ฅผ ์ํด์ reqwest
์ ๊ฐ์ HTTP ํด๋ผ์ด์ธํธ๊ฐ ํ์ํฉ๋๋ค. ์๋ก์ด ๋ก์ปฌ ํ๋ก์ ํธ๋ฅผ ๋ง๋ค๊ณ reqwest
๋ฅผ ์ข
์์ฑ์ ์ถ๊ฐํ์ญ์์
Let us use our new knowledge to create a multi-threaded link checker. It should start at a webpage and check that links on the page are valid. It should recursively check other pages on the same domain and keep doing this until all pages have been validated.
For this, you will need an HTTP client such as
reqwest
. Create a new Cargo project andreqwest
it as a dependency with:
$ cargo new link-checker
$ cd link-checker
$ cargo add --features blocking, rustls-tls reqwest
๋ง์ผ
cargo add
์ปค๋งจ๋๊ฐerror: no such subcommand
๋ก ์คํจํ๋ค๋ฉดCargo.toml
ํ์ผ์ ์ง์ ์์ ํด๋ ๋ฉ๋๋ค. ์๋์ ์ ์ฒด ์ข ์์ฑ ๋ด์ฉ์ด ์์ต๋๋ค.
๋งํฌ๋ฅผ ์ฐพ๊ธฐ ์ํด์ scraper
๋ ์ถ๊ฐํฉ๋๋ค:
If
cargo add
fails witherror: no such subcommand
, then please edit theCargo.toml
file by hand. Add the dependencies listed below.You will also need a way to find links. We can use
scraper
for that:
$ cargo add scraper
๋ง์ง๋ง์ผ๋ก ์ค๋ฅ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ์ผ๋ก thiserror
๋ ์ถ๊ฐํฉ๋๋ค:
Finally, weโll need some way of handling errors. We
thiserror
for that:
$ cargo add thiserror
๋ชจ๋ cargo add
์ด ๋๋๋ฉด Cargo.toml
์ ์๋ ๋ด์ฉ์ด ์ถ๊ฐ ๋์์ต๋๋ค:
The
cargo add
calls will update theCargo.toml
file to look like this:
# ์ค์ต ์ ๋ฒ์ ์ ๋ค๋ฅผ ์ ์์ต๋๋ค.
[dependencies]
reqwest = { version = "0.11.12", features = ["blocking", "rustls-tls"] }
scraper = "0.13.0"
thiserror = "1.0.37"
์ด์ https://www.google.org/
๊ฐ์ ์น ํ์ด์ง๋ฅผ ํ์ํ ์ ์์ต๋๋ค.
You can now download the start page. Try with a small site such as
https://www.google.org/
.
rc/main.rs
ํ์ผ์ ์๋์ ๊ฐ์ต๋๋ค:
Your
src/main.rs
file should look something like this:
use reqwest::blocking::{get, Response}; use reqwest::Url; use scraper::{Html, Selector}; use thiserror::Error; #[derive(Error, Debug)] enum Error { #[error("request error: {0}")] ReqwestError(#[from] reqwest::Error), } fn extract_links(response: Response) -> Result<Vec<Url>, Error> { let base_url = response.url().to_owned(); let document = response.text()?; let html = Html::parse_document(&document); let selector = Selector::parse("a").unwrap(); let mut valid_urls = Vec::new(); for element in html.select(&selector) { if let Some(href) = element.value().attr("href") { match base_url.join(href) { Ok(url) => valid_urls.push(url), Err(err) => { println!("On {base_url}: could not parse {href:?}: {err} (ignored)",); } } } } Ok(valid_urls) } fn main() { let start_url = Url::parse("https://www.google.org").unwrap(); let response = get(start_url).unwrap(); match extract_links(response) { Ok(links) => println!("Links: {links:#?}"), Err(err) => println!("Could not extract links: {err:#}"), } }
์๋ ์ปค๋งจ๋๋ก ์์ค๋ฅผ ์คํํฉ๋๋ค:
Run the code in
src/main.rs
with
$ cargo run
Tasks
- ์ค๋ ๋๋ฅผ ์ฌ์ฉํ์ฌ ๋งํฌ๋ฅผ ๋ณ๋ ฌ๋ก ํ์ธํฉ๋๋ค: URL์ ์ฑ๋๋ก ๋ณด๋ด์ ๋ช ๊ฐ์ ์ค๋ ๋๊ฐ URL์ ๋ณ๋ ฌ๋ก ์ฒดํฌํ๋๋ก ํฉ๋๋ค.
www.google.org
๋๋ฉ์ธ์ ๋ชจ๋ ํ์ด์ง๋ฅผ ์ฌ๊ท์ ์ผ๋ก ํ์ธํ๊ธฐ ์ํด ์ฝ๋๋ฅผ ํ์ฅํด์ ์์ฑํฉ๋๋ค: ์ฌ์ดํธ์ ์ํด ์ฐจ๋จ๋์ง ์๋๋ก 100ํ์ด์ง ์ ๋๋ก ์ ํ์ ๋์๊ธฐ ๋ฐ๋๋๋ค.
- Use threads to check the links in parallel: send the URLs to be checked to a channel and let a few threads check the URLs in parallel.
- Extend this to recursively extract links from all pages on the
www.google.org
domain. Put an upper limit of 100 pages or so so that you donโt end up being blocked by the site.
์ญ์ฃผ
- ๊ธฐ๋ณธ ์์ค๋ ํ๋ฒ์ ํ ๋งํฌ์ฉ ํ์ธํ๋ ์์ค ์ ๋๋ค.
- ์ด๋ฅผ ์ค๋ ๋๋ฅผ ์ฌ์ฉํ์ฌ ๋ณ๋ ฌํ ํ๋ ์ฝ๋๋ฅผ ์์ฑํ์๋ฉด ๋ฉ๋๋ค.
Android
๋ฌ์คํธ๋ ์๋๋ก์ด๋ ๋ค์ดํฐ๋ธ ํ๋ซํผ ๊ฐ๋ฐ์ ์ง์ํฉ๋๋ค. ์ฆ, ๊ธฐ์กด ์๋น์ค๋ฅผ ํ์ฅ ํ ๋ฟ ์๋๋ผ ์๋ก์ด OS์๋น์ค๋ฅผ ์์ฑํ ์ ์์์ ๋ปํฉ๋๋ค.
Rust is supported for native platform development on Android. This means that you can write new operating system services in Rust, as well as extending existing services.
Setup
Android Virtual Device๋ฅผ ์ฌ์ฉํ์ฌ ์ฝ๋๋ฅผ ํ ์คํธํฉ๋๋ค. ์ก์ธ์ค ๊ถํ์ด ์๋์ง ํ์ธํ๊ฑฐ๋ ๋ค์์ ์ฌ์ฉํ์ฌ ์ ์ก์ธ์ค ๊ถํ์ ๋ง๋์ญ์์ค:
We will be using an Android Virtual Device to test our code. Make sure you have access to one or create a new one with:
$ source build/envsetup.sh
$ lunch aosp_cf_x86_64_phone-userdebug
$ acloud create
์์ธํ ๋ด์ฉ์ Android Developer Codelab์ ์ฐธ์กฐํ์ญ์์ค.
Please see the Android Developer Codelab for details.
Build Rules
์๋๋ก์ด๋ ๋น๋ ์์คํ (Soong)์ ๋ค์๊ณผ ๊ฐ์ ์ฌ๋ฌ ๋ชจ๋์ ํตํด ๋ฌ์คํธ๋ฅผ ์ง์ํ๋ค:
Module Type | Description |
---|---|
rust_binary | ๋ฌ์คํธ ๋ฐ์ด๋๋ฆฌ(Rust binary)๋ฅผ ์์ฑํฉ๋๋ค. |
rust_library | ๋ฌ์คํธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์์ฑํ๊ณ , rlib ์ dylib variants๋ฅผ ์ ๊ณตํฉ๋๋ค. |
rust_ffi | cc ๋ชจ๋์์ ์ฌ์ฉํ ์ ์๋ Rust C library๋ฅผ ์์ฑํ๊ณ , static and shared variants๋ฅผ ์ ๊ณตํฉ๋๋ค. |
rust_proc_macro | proc-macro Rust library๋ฅผ ์์ฑํฉ๋๋ค. ์ปดํ์ผ๋ฌ ํ๋ฌ๊ทธ์ธ๊ณผ ์ ์ฌํฉ๋๋ค. |
rust_test | standard Rust test harness๋ฅผ ์ฌ์ฉํ๋ ๋ฌ์คํธ ํ ์คํธ ๋ฐ์ด๋๋ฆฌ๋ฅผ ์์ฑํฉ๋๋ค. |
rust_fuzz | libfuzzer ๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌ์คํธ fuzz ๋ฐ์ด๋๋ฆฌ๋ฅผ ์์ฑํฉ๋๋ค. |
rust_protobuf | ์์ค๋ฅผ ์์ฑํ๊ณ ํน์ protobuf์ ๋ํ ์ธํฐํ์ด์ค๋ฅผ ์ ๊ณตํ๋ ๋ฌ์คํธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์์ฑํฉ๋๋ค. |
rust_bindgen | ์์ค๋ฅผ ์์ฑํ๊ณ C ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋ํ ๋ฌ์คํธ ๋ฐ์ธ๋ฉ์ ํฌํจํ๋ ๋ฌ์คํธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์์ฑํฉ๋๋ค |
๋ค์์ rust_binary
์ rust_library
๋ฅผ ์ดํด๋ด
๋๋ค.
The Android build system (Soong) supports Rust via a number of modules:
Module Type Description rust_binary
Produces a Rust binary. rust_library
Produces a Rust library, and provides both rlib
anddylib
variants.rust_ffi
Produces a Rust C library usable by cc
modules, and provides both static and shared variants.rust_proc_macro
Produces a proc-macro
Rust library. These are analogous to compiler plugins.rust_test
Produces a Rust test binary that uses the standard Rust test harness. rust_fuzz
Produces a Rust fuzz binary leveraging libfuzzer
.rust_protobuf
Generates source and produces a Rust library that provides an interface for a particular protobuf. rust_bindgen
Generates source and produces a Rust library containing Rust bindings to C libraries. We will look at
rust_binary
andrust_library
next.
Rust Binaries
๊ฐ๋จํ ์์ฉ ํ๋ก๊ทธ๋จ์ผ๋ก ์์ํด ๋ณด๊ฒ ์ต๋๋ค. AOSP ์ฒดํฌ์์์ ๋ฃจํธ์์ ๋ค์ ํ์ผ์ ์์ฑํฉ๋๋ค:
Let us start with a simple application. At the root of an AOSP checkout, create the following files:
hello_rust/Android.bp:
rust_binary {
name: "hello_rust",
crate_name: "hello_rust",
srcs: ["src/main.rs"],
}
hello_rust/src/main.rs:
//! Rust demo. /// Prints a greeting to standard output. fn main() { println!("Hello from Rust!"); }
์ด์ ๋ฐ์ด๋๋ฆฌ๋ฅผ ๋น๋, ํธ์, ์คํํ ์ ์์ต๋๋ค:
You can now build, push, and run the binary:
$ m hello_rust
$ adb push $ANDROID_PRODUCT_OUT/system/bin/hello_rust /data/local/tmp
$ adb shell /data/local/tmp/hello_rust
Hello from Rust!
Rust Libraries
rust_library
๋ฅผ ์ฌ์ฉํ์ฌ Android์ฉ ์ Rust ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋ง๋ญ๋๋ค.
์ฌ๊ธฐ์ 2๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์์กด์ฑ์ ์ค์ธํฉ๋๋ค.
- ์๋์ ์ ์ํ
libgreeting
external/rust/crates/
์ ์กด์ฌํ๋libtextwrap
You use
rust_library
to create a new Rust library for Android.Here we declare a dependency on two libraries:
libgreeting
, which we define below,libtextwrap
, which is a crate already vendored inexternal/rust/crates/
.
hello_rust/Android.bp:
rust_binary {
name: "hello_rust_with_dep",
crate_name: "hello_rust_with_dep",
srcs: ["src/main.rs"],
rustlibs: [
"libgreetings",
"libtextwrap",
],
prefer_rlib: true,
}
rust_library {
name: "libgreetings",
crate_name: "greetings",
srcs: ["src/lib.rs"],
}
hello_rust/src/main.rs:
//! Rust demo.
use greetings::greeting;
use textwrap::fill;
/// Prints a greeting to standard output.
fn main() {
println!("{}", fill(&greeting("Bob"), 24));
}
hello_rust/src/lib.rs:
//! Greeting library.
/// Greet `name`.
pub fn greeting(name: &str) -> String {
format!("Hello {name}, it is very nice to meet you!")
}
์ด์ ์ด์ ๊ณผ ๊ฐ์ด ๋ฐ์ด๋๋ฆฌ๋ฅผ ๋น๋, ํธ์, ์คํํ ์ ์์ต๋๋ค: You build, push, and run the binary like before:
$ m hello_rust_with_dep
$ adb push $ANDROID_PRODUCT_OUT/system/bin/hello_rust_with_dep /data/local/tmp
$ adb shell /data/local/tmp/hello_rust_with_dep
Hello Bob, it is very
nice to meet you!
AIDL
๋ฌ์คํธ๋ ์๋๋ก์ด๋ ์ธํฐํ์ด์ค ์ ์ ์ธ์ด(AIDL)์ ์ง์ํฉ๋๋ค:
- ๋ฌ์คํธ ์ฝ๋๋ ๊ธฐ์กด AIDL ์๋ฒ๋ฅผ ํธ์ถ ํ ์ ์์ต๋๋ค.
- ๋ฌ์คํธ์์ ์๋ก์ด AIDL ์๋ฒ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
The Android Interface Definition Language (AIDL) is supported in Rust:
- Rust code can call existing AIDL servers,
- You can create new AIDL servers in Rust.
AIDL Interfaces
AIDL ์ธํฐํ์ด์ค๋ฅผ ์ด์ฉํด์ ์๋น์ค์ API๋ฅผ ์ ์ธํฉ๋๋ค:
You declare the API of your service using an AIDL interface:
birthday_service/aidl/com/example/birthdayservice/IBirthdayService.aidl:
package com.example.birthdayservice;
/** Birthday service interface. */
interface IBirthdayService {
/** Generate a Happy Birthday message. */
String wishHappyBirthday(String name, int years);
}
birthday_service/aidl/Android.bp:
aidl_interface {
name: "com.example.birthdayservice",
srcs: ["com/example/birthdayservice/*.aidl"],
unstable: true,
backend: {
rust: { // Rust is not enabled by default
enabled: true,
},
},
}
AIDL ํ์ผ์ด ๋ฒค๋ ํํฐ์
์ ๋ฐ์ด๋๋ฆฌ์์ ์ฌ์ฉ๋๋ ๊ฒฝ์ฐ vendor_available: true
๋ฅผ ์ถ๊ฐํฉ๋๋ค.
Add
vendor_available: true
if your AIDL file is used by a binary in the vendor partition.
Service Implementation
์ด์ AIDL์๋น์ค๋ฅผ ๊ตฌํํ ์ ์์ต๋๋ค:
We can now implement the AIDL service:
birthday_service/src/lib.rs:
//! Implementation of the `IBirthdayService` AIDL interface.
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::IBirthdayService;
use com_example_birthdayservice::binder;
/// The `IBirthdayService` implementation.
pub struct BirthdayService;
impl binder::Interface for BirthdayService {}
impl IBirthdayService for BirthdayService {
fn wishHappyBirthday(&self, name: &str, years: i32) -> binder::Result<String> {
Ok(format!(
"Happy Birthday {name}, congratulations with the {years} years!"
))
}
}
birthday_service/Android.bp:
rust_library {
name: "libbirthdayservice",
srcs: ["src/lib.rs"],
crate_name: "birthdayservice",
rustlibs: [
"com.example.birthdayservice-rust",
"libbinder_rs",
],
}
AIDL Server
๋ง์ง๋ง์ผ๋ก ์๋น์ค๋ฅผ ์ ๊ณตํ๋ ์๋ฒ๋ฅผ ๋ง๋ค ์ ์์ต๋๋ค:
Finally, we can create a server which exposes the service:
birthday_service/src/server.rs:
//! Birthday service.
use birthdayservice::BirthdayService;
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::BnBirthdayService;
use com_example_birthdayservice::binder;
const SERVICE_IDENTIFIER: &str = "birthdayservice";
/// Entry point for birthday service.
fn main() {
let birthday_service = BirthdayService;
let birthday_service_binder = BnBirthdayService::new_binder(
birthday_service,
binder::BinderFeatures::default(),
);
binder::add_service(SERVICE_IDENTIFIER, birthday_service_binder.as_binder())
.expect("Failed to register service");
binder::ProcessState::join_thread_pool()
}
birthday_service/Android.bp:
rust_binary {
name: "birthday_server",
crate_name: "birthday_server",
srcs: ["src/server.rs"],
rustlibs: [
"com.example.birthdayservice-rust",
"libbinder_rs",
"libbirthdayservice",
],
prefer_rlib: true,
}
Deploy
์๋น์ค๋ฅผ ๋น๋, ํธ์, ์์ ํ ์ ์์ต๋๋ค:
We can now build, push, and start the service:
$ m birthday_server
$ adb push $ANDROID_PRODUCT_OUT/system/bin/birthday_server /data/local/tmp
$ adb shell /data/local/tmp/birthday_server
๋ค๋ฅธ ํฐ๋ฏธ๋์์ ์๋น์ค ๊ตฌ๋์ ํ์ธํฉ๋๋ค:
In another terminal, check that the service runs:
$ adb shell service check birthdayservice
Service birthdayservice: found
service call
๋ก ์๋น์ค๋ฅผ ํธ์ถํ ์๋ ์์ต๋๋ค:
You can also call the service with
service call
:
$ $ adb shell service call birthdayservice 1 s16 Bob i32 24
Result: Parcel(
0x00000000: 00000000 00000036 00610048 00700070 '....6...H.a.p.p.'
0x00000010: 00200079 00690042 00740072 00640068 'y. .B.i.r.t.h.d.'
0x00000020: 00790061 00420020 0062006f 0020002c 'a.y. .B.o.b.,. .'
0x00000030: 006f0063 0067006e 00610072 00750074 'c.o.n.g.r.a.t.u.'
0x00000040: 0061006c 00690074 006e006f 00200073 'l.a.t.i.o.n.s. .'
0x00000050: 00690077 00680074 00740020 00650068 'w.i.t.h. .t.h.e.'
0x00000060: 00320020 00200034 00650079 00720061 ' .2.4. .y.e.a.r.'
0x00000070: 00210073 00000000 's.!..... ')
AIDL Client
๋ง์ง๋ง์ผ๋ก, ์๋ก์ด ์๋น์ค๋ฅผ ์ํ ๋ฌ์คํธ ํด๋ผ์ด์ธํธ๋ฅผ ๋ง๋ค ์ ์์ต๋๋ค.
Finally, we can create a Rust client for our new service.
birthday_service/src/client.rs:
//! Birthday service.
use com_example_birthdayservice::aidl::com::example::birthdayservice::IBirthdayService::IBirthdayService;
use com_example_birthdayservice::binder;
const SERVICE_IDENTIFIER: &str = "birthdayservice";
/// Connect to the BirthdayService.
pub fn connect() -> Result<binder::Strong<dyn IBirthdayService>, binder::StatusCode> {
binder::get_interface(SERVICE_IDENTIFIER)
}
/// Call the birthday service.
fn main() -> Result<(), binder::Status> {
let name = std::env::args()
.nth(1)
.unwrap_or_else(|| String::from("Bob"));
let years = std::env::args()
.nth(2)
.and_then(|arg| arg.parse::<i32>().ok())
.unwrap_or(42);
binder::ProcessState::start_thread_pool();
let service = connect().expect("Failed to connect to BirthdayService");
let msg = service.wishHappyBirthday(&name, years)?;
println!("{msg}");
Ok(())
}
birthday_service/Android.bp:
rust_binary {
name: "birthday_client",
crate_name: "birthday_client",
srcs: ["src/client.rs"],
rustlibs: [
"com.example.birthdayservice-rust",
"libbinder_rs",
],
prefer_rlib: true,
}
ํด๋ผ์ด์ธํธ๋ libbirthdayservice
์ ์์กดํ์ง ์์ต๋๋ค.
์ฅ์น์์ ๋น๋, ํธ์, ์คํํฉ๋๋ค:
Notice that the client does not depend on
libbirthdayservice
.Build, push, and run the client on your device:
$ m birthday_client
$ adb push $ANDROID_PRODUCT_OUT/system/bin/birthday_client /data/local/tmp
$ adb shell /data/local/tmp/birthday_client Charlie 60
Happy Birthday Charlie, congratulations with the 60 years!
Changing API
API๋ฅผ ํ์ฅํ์ฌ ๋ ๋ง์ ๊ธฐ๋ฅ์ ์ ๊ณตํฉ๋๋ค. ํด๋ผ์ด์ธํธ๊ฐ ์์ผ ์นด๋์ ๋ํ ์ค ๋ชฉ๋ก์ ์ง์ ํ ์ ์๋๋ก ํฉ๋๋ค:
Let us extend the API with more functionality: we want to let clients specify a l> ist of lines for the birthday card:
package com.example.birthdayservice;
/** Birthday service interface. */
interface IBirthdayService {
/** Generate a Happy Birthday message. */
String wishHappyBirthday(String name, int years, in String[] text);
}
Logging
log
ํฌ๋ ์ดํธ๋ฅผ ์ฌ์ฉํ์ฌ logcat
(์ฅ์น)๋ stdout
(ํธ์คํธ)์์ ์๋์ผ๋ก ๋ก๊ทธ๋ฅผ ๊ธฐ๋กํ๋๋ก ํฉ๋๋ค:
You should use the
log
crate to automatically log tologcat
(on-device) orstdout
(on-host):
hello_rust_logs/Android.bp:
rust_binary {
name: "hello_rust_logs",
crate_name: "hello_rust_logs",
srcs: ["src/main.rs"],
rustlibs: [
"liblog_rust",
"liblogger",
],
prefer_rlib: true,
host_supported: true,
}
hello_rust_logs/src/main.rs:
//! Rust logging demo.
use log::{debug, error};
/// Logs a greeting.
fn main() {
logger::init(
logger::Config::default()
.with_tag_on_device("rust")
.with_min_level(log::Level::Trace),
);
debug!("Starting program.");
error!("Something went wrong!");
}
์ฅ์น์์ ๋ฐ์ด๋๋ฆฌ๋ฅผ ๋น๋, ํธ์, ์คํํฉ๋๋ค:
Build, push, and run the binary on your device:
$ m hello_rust_logs
$ adb push $ANDROID_PRODUCT_OUT/system/bin/hello_rust_logs /data/local/tmp
$ adb shell /data/local/tmp/hello_rust_logs
adb logcat
์ปค๋งจ๋๋ก ๋ก๊ทธ๋ฅผ ํ์ธํฉ๋๋ค:
The logs show up in
adb logcat
:
$ adb logcat -s rust
09-08 08:38:32.454 2420 2420 D rust: hello_rust_logs: Starting program.
09-08 08:38:32.454 2420 2420 I rust: hello_rust_logs: Things are going fine.
09-08 08:38:32.454 2420 2420 E rust: hello_rust_logs: Something went wrong!
Interoperability
๋ฌ์คํธ๋ ๋ค๋ฅธ ์ธ์ด์์ ์ํธ์ด์ฉ์ฑ์ ํ๋ฅญํ ์ง์ํฉ๋๋ค. ์ฆ, ๋ค์์ ์ํํ ์ ์์ต๋๋ค:
- ํ ์ธ์ด์์ rust ํจ์๋ฅผ ํธ์ถํฉ๋๋ค.
- ํ ์ธ์ด์ ํจ์๋ฅผ ๋ฌ์คํธ์์ ํธ์ถํฉ๋๋ค.
ํ ์ธ์ด์ ํจ์๋ฅผ ํธ์ถํด์ ์ฌ์ฉํ๋ ๊ฒ์ FFI(foreign function interface)๋ผ๊ณ ํฉ๋๋ค.
Rust has excellent support for interoperability with other languages. This means that you can:
- Call Rust functions from other languages.
- Call functions written in other languages from Rust.
When you call functions in a foreign language we say that youโre using a foreign function interface, also known as FFI.
Interoperability with C
๋ฌ์คํธ๋ C ํธ์ถ๊ท์ฝ๊ณผ ํจ๊ป ๊ฐ์ฒด ํ์ผ์ ์ฐ๊ฒฐํ๋ ๊ฒ์ ์๋ฒฝํ๊ฒ ์ง์ํฉ๋๋ค. ๋ฐ๋๋ก ๋ฌ์คํธ ํจ์๋ฅผ ๋ด๋ณด๋ด์ C์์ ํธ์ถ ํ ์ ์์ต๋๋ค.
์ํ๋ ๊ฒฝ์ฐ ์ง์ ์ฝ๋ฉํ ์ ์์ต๋๋ค:
Rust has full support for linking object files with a C calling convention. Similarly, you can export Rust functions and call them from C.
You can do it by hand if you want:
extern "C" { fn abs(x: i32) -> i32; } fn main() { let x = -42; let abs_x = unsafe { abs(x) }; println!("{x}, {abs_x}"); }
์ฐ๋ฆฌ๋ ์ด๋ฏธSafe FFI ๋ํผ ์ฐ์ต๋ฌธ์ ์์ ์ด๋ฅผ ๋ค๋ฃจ์์ต๋๋ค.
์ด๋ ๋์ ํ๋ซํผ์ ๋ํ ์์ ํ ์ง์์ ์ ์ ๋ก ํฉ๋๋ค. ์ค ์ ํ์๋ ๊ถ์ฅํ์ง ์์ต๋๋ค.
๋ค์์ผ๋ก ์ข ๋ ๋์ ์ต์ ์ ์ดํด๋ณด๊ฒ ์ต๋๋ค.
We already saw this in the Safe FFI Wrapper exercise.
This assumes full knowledge of the target platform. Not recommended for production.
We will look at better options next.
Using Bindgen
bindgen๋ C ํค๋ํ์ผ์์ ์๋์ผ๋ก ์์ฑํ๋ ๋๊ตฌ์ ๋๋ค.
The bindgen tool can auto-generate bindings from a C header file.
์์ C๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์์ฑํฉ๋๋ค:
First create a small C library:
interoperability/bindgen/libbirthday.h:
typedef struct card {
const char* name;
int years;
} card;
void print_card(const card* card);
interoperability/bindgen/libbirthday.c:
#include <stdio.h>
#include "libbirthday.h"
void print_card(const card* card) {
printf("+--------------\n");
printf("| Happy Birthday %s!\n", card->name);
printf("| Congratulations with the %i years!\n", card->years);
printf("+--------------\n");
}
Android.bp
ํ์ผ์ ์๋๋ฅผ ์ถ๊ฐํฉ๋๋ค:
Add this to your
Android.bp
file:
interoperability/bindgen/Android.bp:
cc_library {
name: "libbirthday",
srcs: ["libbirthday.c"],
}
๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋ํ ๋ํผ ํค๋ ํ์ผ์ ๋ง๋ญ๋๋ค(์ด ์์์์๋ ํ์ํ์ง ์์ต๋๋ค):
Create a wrapper header file for the library (not strictly needed in this example):
interoperability/bindgen/libbirthday_wrapper.h:
#include "libbirthday.h"
์ด์ ๋ฐ์ธ๋ฉ์ ์๋์ผ๋ก ์์ฑํ ์ ์์ต๋๋ค:
You can now auto-generate the bindings:
interoperability/bindgen/Android.bp:
rust_bindgen {
name: "libbirthday_bindgen",
crate_name: "birthday_bindgen",
wrapper_src: "libbirthday_wrapper.h",
source_stem: "bindings",
static_libs: ["libbirthday"],
}
๋ง์นจ๋ด, ๋ฌ์คํธ ํ๋ก๊ทธ๋จ์์ ๋ฐ์ธ๋ฉ์ ์ฌ์ฉํ ์ ์์ต๋๋ค:
Finally, we can use the bindings in our Rust program:
interoperability/bindgen/Android.bp:
rust_binary {
name: "print_birthday_card",
srcs: ["main.rs"],
rustlibs: ["libbirthday_bindgen"],
}
interoperability/bindgen/main.rs:
//! Bindgen demo. use birthday_bindgen::{card, print_card}; fn main() { let name = std::ffi::CString::new("Peter").unwrap(); let card = card { name: name.as_ptr(), years: 42, }; unsafe { print_card(&card as *const card); } }
Build, push, and run the binary on your device:
$ m print_birthday_card
$ adb push $ANDROID_PRODUCT_OUT/system/bin/print_birthday_card /data/local/tmp
$ adb shell /data/local/tmp/print_birthday_card
๋ง์ง๋ง์ผ๋ก, ๋ฐ์ธ๋ฉ์ด ์๋ํ๋์ง ์๋์์ฑ ํ ์คํธ๋ฅผ ์คํํ ์ ์์ต๋๋ค:
Finally, we can run auto-generated tests to ensure the bindings work:
interoperability/bindgen/Android.bp:
rust_test {
name: "libbirthday_bindgen_test",
srcs: [":libbirthday_bindgen"],
crate_name: "libbirthday_bindgen_test",
test_suites: ["general-tests"],
auto_gen_config: true,
clippy_lints: "none", // Generated file, skip linting
lints: "none",
}
$ atest libbirthday_bindgen_test
Calling Rust
๋ฌ์คํธ์์ ํ์ ๊ณผ ํจ์๋ฅผ C๋ก ๋ด๋ณด๋ด๋ ๊ฒ์ ๊ฐ๋จํฉ๋๋ค:
Exporting Rust functions and types to C is easy:
interoperability/rust/libanalyze/analyze.rs
//! Rust FFI demo. #![deny(improper_ctypes_definitions)] use std::os::raw::c_int; /// Analyze the numbers. #[no_mangle] pub extern "C" fn analyze_numbers(x: c_int, y: c_int) { if x < y { println!("x ({x}) is smallest!"); } else { println!("y ({y}) is probably larger than x ({x})"); } }
interoperability/rust/libanalyze/analyze.h
#ifndef ANALYSE_H
#define ANALYSE_H
extern "C" {
void analyze_numbers(int x, int y);
}
#endif
interoperability/rust/libanalyze/Android.bp
rust_ffi {
name: "libanalyze_ffi",
crate_name: "analyze_ffi",
srcs: ["analyze.rs"],
include_dirs: ["."],
}
์ด์ C๋ฐ์ด๋๋ฆฌ์์ ํธ์ถํ ์ ์์ต๋๋ค:
We can now call this from a C binary:
interoperability/rust/analyze/main.c
#include "analyze.h"
int main() {
analyze_numbers(10, 20);
analyze_numbers(123, 123);
return 0;
}
interoperability/rust/analyze/Android.bp
cc_binary {
name: "analyze_numbers",
srcs: ["main.c"],
static_libs: ["libanalyze_ffi"],
}
์ฅ์น์์ ๋ฐ์ด๋๋ฆฌ๋ฅผ ๋น๋, ํธ์, ์คํํด๋ด ๋๋ค:
Build, push, and run the binary on your device:
$ m analyze_numbers
$ adb push $ANDROID_PRODUCT_OUT/system/bin/analyze_numbers /data/local/tmp
$ adb shell /data/local/tmp/analyze_numbers
With C++
CXX ํฌ๋ ์ดํธ๋ ๋ฌ์คํธ์ C++ ์ฌ์ด์ ์์ ํ ์ํธ์ด์ฉ์ฑ์ ๊ฐ๋ฅํ๊ฒ ํด์ค๋๋ค.
์ ์ฒด์ ์ธ ์ ๊ทผ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค.
The CXX crate makes it possible to do safe interoperability between Rust and C++.
The overall approach looks like this:
์ฌ์ฉํ๋ ๋ฐฉ๋ฒ์ ๋ํด์๋CXX ํํ ๋ฆฌ์ผ ๋ฅผ ์ฐธ์กฐํฉ๋๋ค.
See the CXX tutorial for an full example of using this.
Interoperability with Java
์๋ฐ๋ Java Native Interface(JNI)๋ฅผ ํตํด ๊ณต์ ๊ฐ์ฒด๋ฅผ ๋ก๋ํ ์ ์์ต๋๋ค. jni
ํฌ๋ ์ดํธ๋ฅผ ์ฌ์ฉํ์ฌ ํธํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋ง๋ค ์ ์์ต๋๋ค.
Java can load shared objects via Java Native Interface (JNI). The
jni
crate allows you to create a compatible library.
๋จผ์ , ์๋ฐ๋ก ๋ด๋ณด๋ผ ๋ฌ์คํธ ํจ์๋ฅผ ์์ฑํฉ๋๋ค:
First, we create a Rust function to export to Java:
interoperability/java/src/lib.rs:
#![allow(unused)] fn main() { //! Rust <-> Java FFI demo. use jni::objects::{JClass, JString}; use jni::sys::jstring; use jni::JNIEnv; /// HelloWorld::hello method implementation. #[no_mangle] pub extern "system" fn Java_HelloWorld_hello( env: JNIEnv, _class: JClass, name: JString, ) -> jstring { let input: String = env.get_string(name).unwrap().into(); let greeting = format!("Hello, {input}!"); let output = env.new_string(greeting).unwrap(); output.into_inner() } }
interoperability/java/Android.bp:
rust_ffi_shared {
name: "libhello_jni",
crate_name: "hello_jni",
srcs: ["src/lib.rs"],
rustlibs: ["libjni"],
}
๋ง์นจ๋ด, ์๋ฐ์์ ์ด ํจ์๋ฅผ ํธ์ถ ํ ์ ์์ต๋๋ค:
Finally, we can call this function from Java:
interoperability/java/HelloWorld.java:
class HelloWorld {
private static native String hello(String name);
static {
System.loadLibrary("hello_jni");
}
public static void main(String[] args) {
String output = HelloWorld.hello("Alice");
System.out.println(output);
}
}
interoperability/java/Android.bp:
java_binary {
name: "helloworld_jni",
srcs: ["HelloWorld.java"],
main_class: "HelloWorld",
required: ["libhello_jni"],
}
๋ง์ง๋ง์ผ๋ก ๋ฐ์ด๋๋ฆฌ๋ฅผ ๋น๋, ์ฑํฌ, ์คํํฉ๋๋ค:
Finally, you can build, sync, and run the binary:
$ m helloworld_jni
$ adb sync # requires adb root && adb remount
$ adb shell /system/bin/helloworld_jni
Exercises
๋ง์ง๋ง ์ฐ์ต๋ฌธ์ ๋ ๋น์ ์ ํ๋ก์ ํธ ์ค ํ๋๋ฅผ FFI๋ก ๋ฌ์คํธ์ ์ฐ๊ณ ํด๋ณด๋ ๊ฒ์ ๋๋ค. ๋ช๊ฐ์ง ์์์ ๋๋ค:
- ๋น์ ์ AIDL์๋น์ค๋ฅผ ๋ฌ์คํธ ํด๋ผ์ด์ธํธ์์ ํธ์ถํด๋ด ๋๋ค.
- ๋น์ ์ ํ๋ก์ ํธ์ ํจ์๋ฅผ ๋ฌ์คํธ๋ก ์ฎ๊ธฐ๊ณ ํธ์ถํด๋ด ๋๋ค.
For the last exercise, we will look at one of the projects you work with. Let us group up and do this together. Some suggestions:
Call your AIDL service with a client written in Rust.
Move a function from your project to Rust and call it.
Thanks!
Comprehensive Rust ๐ฆ๋ฅผ ์ด์ฉํด ์ฃผ์ ์ ๊ฐ์ฌํฉ๋๋ค. ์ฆ๊ฒ๊ณ ์ ์ตํ ์๊ฐ์ด์๊ธฐ๋ฅผ ๋ฐ๋๋๋ค.
๊ฐ์๊ฐ ์๋ฒฝํ์ง ์์ผ๋ ์ค์๋ ๊ฐ์ ์ ์ด ์๋ค๋ฉด ์ธ์ ๋ ์ง ๊นํ๋ธ๋ก ์ฐ๋ฝ์ฃผ์ธ์
Thank you for taking Comprehensive Rust ๐ฆ! We hope you enjoyed it and that it was useful.
Weโve had a lot of fun putting the course together. The course is not perfect, so if you spotted any mistakes or have ideas for improvements, please get in contact with us on GitHub. We would love to hear from you.
Other Rust Resources
๋ฌ์คํธ ์ปค๋ฎค๋ํฐ๋ ์จ๋ผ์ธ์์ ๊ณ ํ์ง์ ๋ฌด๋ฃ ์์ค๋ฅผ ๋ง๋ค์์ต๋๋ค.
The Rust community has created a wealth of high-quality and free resources online.
Official Documentation
๋ฌ์คํธ ํ๋ก์ ํธ๋ ์ฌ๋ฌ ๋ฆฌ์์ค๋ฅผ ํธ์คํ ํฉ๋๋ค. ์ผ๋ฐ์ ์ธ ๋ด์ฉ์ ๋ค๋ฃจ๋ ๋ช๊ฐ์ง์ ๋๋ค:
The Rust project hosts many resources. These cover Rust in general:
- The Rust Programming Language: ๋ฌ์คํธ์ ๋ํ ๋ฌด๋ฃ ํ์ค ์์ ์ ๋๋ค. ์ธ์ด์ ๋ํ ์์ธํ ์ค๋ช ๊ณผ ์ฌ๋๋ค์ด ๋น๋ ํ ์ ์๋ ๋ช๊ฐ์ง ํ๋ก์ ํธ๋ฅผ ํฌํจํฉ๋๋ค.
- Rust By Example: ์ฌ๋ฌ ์์ ๋ฅผ ํตํด ๋ฌ์คํธ์ ๋ฌธ๋ฒ์ ๋ณด์ฌ์ฃผ๋ฉฐ ๋๋๋ก ์ฝ๋๋ฅผ ํ์ฅํ๋ ์ฝ๊ฐ์ ์ฐ์ต๋ฌธ์ ๋ค์ด ํฌํจ๋์ด ์์ต๋๋ค.
- Rust Standard Library: ๋ฌ์คํธ ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ ์ฒด ๋ฌธ์์ ๋๋ค.
- The Rust Reference: ๋ฉ๋ชจ๋ฆฌ ๋ชจ๋ธ๋ง๊ณผ ๋ฌ์คํธ ๋ฌธ๋ฒ์ ์ค๋ช ํ๋ ๋ฌธ์์ ๋๋ค.(์์ง ๋ถ์์ ํ๋คํจ)
- The Rust Programming Language: the canonical free book about Rust. Covers the language in detail and includes a few projects for people to build.
- Rust By Example: covers the Rust syntax via a series of examples which showcase different constructs. Sometimes includes small exercises where you are asked to expand on the code in the examples.
- Rust Standard Library: full documentation of the standard library for Rust.
- The Rust Reference: an incomplete book which describes the Rust grammar and memory model.
์ข ๋ ์ ๋ฌธ์ ์ธ ๊ณต์ ๊ฐ์ด๋์ ๋๋ค:
More specialized guides hosted on the official Rust site:
- The Rustonomicon: ์์ ํ์ง ์์ ๋ฌ์คํธ, FFI, rawํฌ์ธํฐ ์์ ์ ๋ค๋ฃน๋๋ค.
- Asynchronous Programming in Rust: ๋ฌ์คํธ ๋ถ์ด ์์ฑ ๋ ์ดํ ๋์ ๋ ์๋ก์ด ๋น๋๊ธฐ ํ๋ก๊ทธ๋๋ฐ ๋ชจ๋ธ์ ๋ค๋ฃน๋๋ค.
- The Embedded Rust Book: ์ด์์ฒด์ ๊ฐ ์๋ ์๋ฒ ๋๋ ์ฅ์น์์์ ๋ฌ์คํธ ์ฌ์ฉ๋ฒ์ ์๊ฐํฉ๋๋ค.
- The Rustonomicon: covers unsafe Rust, including working with raw pointers and interfacing with other languages (FFI).
- Asynchronous Programming in Rust: covers the new asynchronous programming model which was introduced after the Rust Book was written.
- The Embedded Rust Book: an introduction to using Rust on embedded devices without an operating system.
Unofficial Learning Material
๋ฌ์คํธ์ ๋ํ ๊ธฐํ ์๋ด์์ ํํ ๋ฆฌ์ผ์ ์ผ๋ถ์ ๋๋ค:
A small selection of other guides and tutorial for Rust:
- Learn Rust the Dangerous Way: C์ธ์ด ํ๋ก๊ทธ๋๋จธ ๊ด์ ์์ ๋ฌ์คํธ๋ฅผ ๋ค๋ฃน๋๋ค.
- Rust for Embedded C Programmers: ์๋ฒ ๋๋ C๊ฐ๋ฐ์(ํ์จ์ด ๊ฐ๋ฐ์)๋ฅผ ์ํ ๋ฌ์คํธ ๊ฐ์ด๋์ ๋๋ค.
- Rust for professionals: ๋ค๋ฅธ ์ธ์ด(C/C++, Java, Python, Javascript)์์ ๋ณ๋ ฌ๋น๊ต๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌ์คํธ ๋ฌธ๋ฒ์ ๋ค๋ฃน๋๋ค.
- Rust on Exercism: ๋ฌ์คํธ๋ฅผ ๋ฐฐ์ฐ๋๋ฐ ๋์์ด ๋๋ 100๊ฐ ์ด์์ ์ฐ์ต๋ฌธ์
- Ferrous Teaching Material: ๋ฌ์คํธ ์ธ์ด์ ๊ธฐ๋ณธ๋ถํฐ ๊ณ ๊ธ์ ์ ๋ถ ๋ค๋ฃจ๋ ์ผ๋ จ์ ์์ ํ๋ ์ ํ ์ด์ , ์น ์ด์ ๋ธ๋ฆฌ, async/await ๊ฐ์ ๋ถ๋ถ๋ ํจ๊ป ๋ค๋ฃน๋๋ค.
- Beginnerโs Series to Rust, Take your first steps with Rust: ์ฒซ๋ฒ์งธ๋ 35๊ฐ์ ์๋ฆฌ์ฆ ์์์ด๋ฉฐ ๋๋ฒ์งธ๋ ๋ฌ์คํธ์ ๋ฌธ๋ฒ๊ณผ ๊ตฌ์กฐ๋ฅผ ๋ค๋ฃจ๋ 11๊ฐ์ ๋ชจ๋ ์ธํธ์ ๋๋ค.
Little Book of Rust Books์์ ๋ ๋ง์ ๋ฌ์คํธ ๋ถ์ ํ์ธํด๋ณด์ธ์.
- Learn Rust the Dangerous Way: covers Rust from the perspective of low-level C programmers.
- Rust for Embedded C Programmers: covers Rust from the perspective of developers who write firmware in C.
- Rust for professionals: covers the syntax of Rust using side-by-side comparisons with other languages such as C, C++, Java, JavaScript, and Python.
- Rust on Exercism: 100+ exercises to help you learn Rust.
- Ferrous Teaching Material: a series of small presentations covering both basic and advanced part of the Rust language. Other topics such as WebAssembly, and async/await are also covered.
- Beginnerโs Series to Rust and Take your first steps with Rust: two Rust guides aimed at new developers. The first is a set of 35 videos and the second is a set of 11 modules which covers Rust syntax and basic constructs.
Please see the Little Book of Rust Books for even more Rust books.
Credits
์ด ์๋ฃ๋ ๋ง์ ํ๋ฅญํ ๋ฌ์คํธ ๋ฌธ์๋ค์ ๋์์ ๋ฐ์ ์์ฑ๋์์ต๋๋ค. ์ ์ฉํ ์๋ฃ์ ์ ์ฒด ๋ชฉ๋ก์ other resources์์ ์ดํด๋ณด์๊ธฐ ๋ฐ๋๋๋ค.
The material here builds on top of the many great sources of Rust documentation. See the page on other resources for a full list of useful resources.
Comprehensive Rust์ ์๋ฃ๋ Apache 2.0 ๋ผ์ด์ ์ค๋ฅผ ๋ฐ๋ฆ
๋๋ค. ์์ธํ๊ฑด LICENSE.txt
ํ์ธํด ๋ณด์๊ธฐ ๋ฐ๋๋๋ค.
The material of Comprehensive Rust is licensed under the terms of the Apache 2.0
license, please see LICENSE.txt
for details.
Rust by Example
์ผ๋ถ ์์ ์ ์ฐ์ต๋ฌธ์ (ํ๋ จ)์Rust by Example์ ์ฐธ์กฐํ์์ต๋๋ค. ๋ผ์ด์ ์ค ์กฐํญ์ ํฌํจํ์ฌ ์ ์ฅ์์ third_party/rust-by-example/
ํด๋๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
Some examples and exercises have been copied and adapted from Rust by Example. Please see the
third_party/rust-by-example/
directory for details, including the license terms.
Rust on Exercism
์ผ๋ถ ์ฐ์ต๋ฌธ์ (ํ๋ จ)์ Rust on Exercism์ ์ฐธ์กฐํ์์ต๋๋ค.
๋ผ์ด์ ์ค ์กฐํญ์ ํฌํจํ์ฌ ์ ์ฅ์์ third_party/rust-on-exercism/
ํด๋๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
Some exercises have been copied and adapted from Rust on Exercism. Please see the
third_party/rust-on-exercism/
directory for details, including the license terms.
CXX
4์ผ์ฐจ ์คํ ๊ฐ์ ์ค Interoperability with C++์์๋ CXX์ ์ด๋ฏธ์ง๋ฅผ ์ฌ์ฉํ์์ต๋๋ค.
๋ผ์ด์ ์ค ์กฐํญ์ ํฌํจํ์ฌ ์ ์ฅ์์ third_party/cxx/
ํด๋๋ฅผ ์ฐธ์กฐํ์๊ธฐ ๋ฐ๋๋๋ค.
The Interoperability with C++ section uses an image from CXX. Please see the
third_party/cxx/
directory for details, including the license terms.
Solutions
์ฐ์ต๋ฌธ์ (ํ๋ จ)์ ์ ๋ต์ ๋ค์ ํ์ด์ง์์ ํ์ธํ ์ ์์ต๋๋ค. ๊นํ๋ธ์์ ์ด์ ๋ํด ์์ ๋กญ๊ฒ ์ง๋ฌธํ์๊ณ ๋ ๋์ ์๋ฃจ์ ์ด ์๋ค๋ฉด ์๋ ค์ฃผ์๊ธฐ ๋ฐ๋๋๋ค.
You will find solutions to the exercises on the following pages.
Feel free to ask questions about the solutions on GitHub. Let us know if you have a different or better solution than what is presented here.
์ฐธ๊ณ :
// ANCHOR: label
๊ณผ// ANCHOR_END: label
์ฃผ์์ ๋ฌธ์ ๋ฅผ ๊ตฌ์ฑํ๊ธฐ ์ํ ๋ฉํ ์ฃผ์์ผ๋ก ๋ฌด์ํ์๋ฉด ๋ฉ๋๋ค.Note: Please ignore the
// ANCHOR: label
and// ANCHOR_END: label
comments you see in the solutions. They are there to make it possible to re-use parts of the solutions as the exercises.
Day 1 Morning Exercises
Arrays and for
Loops
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: transpose fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] { // ANCHOR_END: transpose let mut result = [[0; 3]; 3]; for i in 0..3 { for j in 0..3 { result[j][i] = matrix[i][j]; } } return result; } // ANCHOR: pretty_print fn pretty_print(matrix: &[[i32; 3]; 3]) { // ANCHOR_END: pretty_print for row in matrix { println!("{row:?}"); } } // ANCHOR: tests #[test] fn test_transpose() { let matrix = [ [101, 102, 103], // [201, 202, 203], [301, 302, 303], ]; let transposed = transpose(matrix); assert_eq!( transposed, [ [101, 201, 301], // [102, 202, 302], [103, 203, 303], ] ); } // ANCHOR_END: tests // ANCHOR: main fn main() { let matrix = [ [101, 102, 103], // <-- the comment makes rustfmt add a newline [201, 202, 203], [301, 302, 303], ]; println!("matrix:"); pretty_print(&matrix); let transposed = transpose(matrix); println!("transposed:"); pretty_print(&transposed); }
Bonus question
์ฌ์ค ์ ๋์ํ์ง ์์ต๋๋ค. slice-of-slices (&[&[i32]]
)์ ์
๋ ฅ ํ์
์ผ๋ก ์ฌ์ฉํ์ฌ ๋ชจ๋ ํฌ๊ธฐ์ ํ๋ ฌ์ ์ฒ๋ฆฌํ ์ ์์ต๋๋ค. ํ์ง๋ง ๋ฆฌํด ๊ฐ์ ์์ ํด์ผ ํ๊ธฐ๋๋ฌธ์ &[&[i32]]
ํ์
์ ์ฌ์ฉํ ์ ์์ต๋๋ค.
Vec<Vec<i32>>
์ ๊ฐ์ ํ์
์ ์ฌ์ฉํ๋ ค๊ณ ์๋ํ ์๋ ์์ง๋ง ์ญ์ ์ ๋์ํ์ง ์์ต๋๋ค: Vec<Vec<i32>>
ํ์
์ &[&[i32]]
๋ก ๋ณํํ๋ ๊ฒ์ด ์ด๋ ต๊ธฐ ๋๋ฌธ์ pretty_print
์ ์ฌ์ฉํ๋๋ฐ ์ด๋ ค์์ด ์์ต๋๋ค.
It honestly doesnโt work so well. It might seem that we could use a slice-of-slices (
&[&[i32]]
) as the input type to transpose and thus make our function handle any size of matrix. However, this quickly breaks down: the return type cannot be&[&[i32]]
since it needs to own the data you return.You can attempt to use something like
Vec<Vec<i32>>
, but this doesnโt work very well either: itโs hard to convert fromVec<Vec<i32>>
to&[&[i32]]
so now you cannot easily usepretty_print
either.
Day 1 Afternoon Exercises
Designing a Library
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: setup struct Library { books: Vec<Book>, } struct Book { title: String, year: u16, } impl Book { // This is a constructor, used below. fn new(title: &str, year: u16) -> Book { Book { title: String::from(title), year, } } } // This makes it possible to print Book values with {}. impl std::fmt::Display for Book { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} ({})", self.title, self.year) } } // ANCHOR_END: setup // ANCHOR: Library_new impl Library { fn new() -> Library { // ANCHOR_END: Library_new Library { books: Vec::new() } } // ANCHOR: Library_len //fn len(self) -> usize { // unimplemented!() //} // ANCHOR_END: Library_len fn len(&self) -> usize { self.books.len() } // ANCHOR: Library_is_empty //fn is_empty(self) -> bool { // unimplemented!() //} // ANCHOR_END: Library_is_empty fn is_empty(&self) -> bool { self.books.is_empty() } // ANCHOR: Library_add_book //fn add_book(self, book: Book) { // unimplemented!() //} // ANCHOR_END: Library_add_book fn add_book(&mut self, book: Book) { self.books.push(book) } // ANCHOR: Library_print_books //fn print_books(self) { // unimplemented!() //} // ANCHOR_END: Library_print_books fn print_books(&self) { for book in &self.books { println!("{}", book); } } // ANCHOR: Library_oldest_book //fn oldest_book(self) -> Option<&Book> { // unimplemented!() //} // ANCHOR_END: Library_oldest_book fn oldest_book(&self) -> Option<&Book> { self.books.iter().min_by_key(|book| book.year) } } // ANCHOR: main // ์์ค์ชฝ ์ฃผ์๋ค์ ์ ๊ฑฐํ๊ณ ๋๋ฝ๋ ๋ฉ์๋๋ฅผ ๊ตฌํํ์ธ์. // ๋ฉ์๋ ์ ์๋ ์์ ๋์ด์ผ ํฉ๋๋ค.(self๊ฐ ํฌํจ๋๋๋ก) // This shows the desired behavior. Uncomment the code below and // implement the missing methods. You will need to update the // method signatures, including the "self" parameter! fn main() { let library = Library::new(); //println!("Our library is empty: {}", library.is_empty()); // //library.add_book(Book::new("Lord of the Rings", 1954)); //library.add_book(Book::new("Alice's Adventures in Wonderland", 1865)); // //library.print_books(); // //match library.oldest_book() { // Some(book) => println!("My oldest book is {book}"), // None => println!("My library is empty!"), //} // //println!("Our library has {} books", library.len()); } // ANCHOR_END: main #[test] fn test_library_len() { let mut library = Library::new(); assert_eq!(library.len(), 0); assert!(library.is_empty()); library.add_book(Book::new("Lord of the Rings", 1954)); library.add_book(Book::new("Alice's Adventures in Wonderland", 1865)); assert_eq!(library.len(), 2); assert!(!library.is_empty()); } #[test] fn test_library_is_empty() { let mut library = Library::new(); assert!(library.is_empty()); library.add_book(Book::new("Lord of the Rings", 1954)); assert!(!library.is_empty()); } #[test] fn test_library_print_books() { let mut library = Library::new(); library.add_book(Book::new("Lord of the Rings", 1954)); library.add_book(Book::new("Alice's Adventures in Wonderland", 1865)); // We could try and capture stdout, but let us just call the // method to start with. library.print_books(); } #[test] fn test_library_oldest_book() { let mut library = Library::new(); assert!(library.oldest_book().is_none()); library.add_book(Book::new("Lord of the Rings", 1954)); assert_eq!( library.oldest_book().map(|b| b.title.as_str()), Some("Lord of the Rings") ); library.add_book(Book::new("Alice's Adventures in Wonderland", 1865)); assert_eq!( library.oldest_book().map(|b| b.title.as_str()), Some("Alice's Adventures in Wonderland") ); }
Day 2 Morning Exercises
Points and Polygons
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[derive(Debug, Copy, Clone, PartialEq, Eq)] // ANCHOR: Point pub struct Point { // ANCHOR_END: Point x: i32, y: i32, } // ANCHOR: Point-impl impl Point { // ANCHOR_END: Point-impl pub fn new(x: i32, y: i32) -> Point { Point { x, y } } pub fn magnitude(self) -> f64 { f64::from(self.x.pow(2) + self.y.pow(2)).sqrt() } pub fn dist(self, other: Point) -> f64 { (self - other).magnitude() } } impl std::ops::Add for Point { type Output = Self; fn add(self, other: Self) -> Self::Output { Self { x: self.x + other.x, y: self.y + other.y, } } } impl std::ops::Sub for Point { type Output = Self; fn sub(self, other: Self) -> Self::Output { Self { x: self.x - other.x, y: self.y - other.y, } } } // ANCHOR: Polygon pub struct Polygon { // ANCHOR_END: Polygon points: Vec<Point>, } // ANCHOR: Polygon-impl impl Polygon { // ANCHOR_END: Polygon-impl pub fn new() -> Polygon { Polygon { points: Vec::new() } } pub fn add_point(&mut self, point: Point) { self.points.push(point); } pub fn left_most_point(&self) -> Option<Point> { self.points.iter().min_by_key(|p| p.x).copied() } pub fn iter(&self) -> impl Iterator<Item = &Point> { self.points.iter() } pub fn length(&self) -> f64 { if self.points.is_empty() { return 0.0; } let mut result = 0.0; let mut last_point = self.points[0]; for point in &self.points[1..] { result += last_point.dist(*point); last_point = *point; } result += last_point.dist(self.points[0]); result } } // ANCHOR: Circle pub struct Circle { // ANCHOR_END: Circle center: Point, radius: i32, } // ANCHOR: Circle-impl impl Circle { // ANCHOR_END: Circle-impl pub fn new(center: Point, radius: i32) -> Circle { Circle { center, radius } } pub fn circumference(&self) -> f64 { 2.0 * std::f64::consts::PI * f64::from(self.radius) } pub fn dist(&self, other: &Self) -> f64 { self.center.dist(other.center) } } // ANCHOR: Shape pub enum Shape { Polygon(Polygon), Circle(Circle), } // ANCHOR_END: Shape impl From<Polygon> for Shape { fn from(poly: Polygon) -> Self { Shape::Polygon(poly) } } impl From<Circle> for Shape { fn from(circle: Circle) -> Self { Shape::Circle(circle) } } impl Shape { pub fn circumference(&self) -> f64 { match self { Shape::Polygon(poly) => poly.length(), Shape::Circle(circle) => circle.circumference(), } } } // ANCHOR: unit-tests #[cfg(test)] mod tests { use super::*; fn round_two_digits(x: f64) -> f64 { (x * 100.0).round() / 100.0 } #[test] fn test_point_magnitude() { let p1 = Point::new(12, 13); assert_eq!(round_two_digits(p1.magnitude()), 17.69); } #[test] fn test_point_dist() { let p1 = Point::new(10, 10); let p2 = Point::new(14, 13); assert_eq!(round_two_digits(p1.dist(p2)), 5.00); } #[test] fn test_point_add() { let p1 = Point::new(16, 16); let p2 = p1 + Point::new(-4, 3); assert_eq!(p2, Point::new(12, 19)); } #[test] fn test_polygon_left_most_point() { let p1 = Point::new(12, 13); let p2 = Point::new(16, 16); let mut poly = Polygon::new(); poly.add_point(p1); poly.add_point(p2); assert_eq!(poly.left_most_point(), Some(p1)); } #[test] fn test_polygon_iter() { let p1 = Point::new(12, 13); let p2 = Point::new(16, 16); let mut poly = Polygon::new(); poly.add_point(p1); poly.add_point(p2); let points = poly.iter().cloned().collect::<Vec<_>>(); assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]); } #[test] fn test_shape_circumferences() { let mut poly = Polygon::new(); poly.add_point(Point::new(12, 13)); poly.add_point(Point::new(17, 11)); poly.add_point(Point::new(16, 16)); let shapes = vec![ Shape::from(poly), Shape::from(Circle::new(Point::new(10, 20), 5)), ]; let circumferences = shapes .iter() .map(Shape::circumference) .map(round_two_digits) .collect::<Vec<_>>(); assert_eq!(circumferences, vec![15.48, 31.42]); } } // ANCHOR_END: unit-tests #[allow(dead_code)] fn main() {}
Day 2 Afternoon Exercises
Luhn Algorithm
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: luhn pub fn luhn(cc_number: &str) -> bool { // ANCHOR_END: luhn let mut digits_seen = 0; let mut sum = 0; for (i, ch) in cc_number.chars().rev().filter(|&ch| ch != ' ').enumerate() { match ch.to_digit(10) { Some(d) => { sum += if i % 2 == 1 { let dd = d * 2; dd / 10 + dd % 10 } else { d }; digits_seen += 1; } None => return false, } } if digits_seen < 2 { return false; } sum % 10 == 0 } fn main() { let cc_number = "1 0"; println!( "Is {} a valid credit card number? {}", cc_number, if luhn(cc_number) { "yes" } else { "no" } ); } // ANCHOR: unit-tests #[test] fn test_non_digit_cc_number() { assert!(!luhn("foo")); } #[test] fn test_empty_cc_number() { assert!(!luhn("")); assert!(!luhn(" ")); assert!(!luhn(" ")); assert!(!luhn(" ")); } #[test] fn test_single_digit_cc_number() { assert!(!luhn("0")); } #[test] fn test_two_digit_cc_number() { assert!(luhn(" 0 0 ")); } #[test] fn test_valid_cc_number() { assert!(luhn("4263 9826 4026 9299")); assert!(luhn("4539 3195 0343 6467")); assert!(luhn("7992 7398 713")); } #[test] fn test_invalid_cc_number() { assert!(!luhn("4223 9826 4026 9299")); assert!(!luhn("4539 3195 0343 6476")); assert!(!luhn("8273 1232 7352 0569")); } // ANCHOR_END: unit-tests
Strings and Iterators
#![allow(unused)] fn main() { // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: prefix_matches pub fn prefix_matches(prefix: &str, request_path: &str) -> bool { // ANCHOR_END: prefix_matches let mut prefixes = prefix.split('/'); let request_paths = request_path .split('/') .map(|p| Some(p)) .chain(std::iter::once(None)); for (prefix, request_path) in prefixes.zip(request_paths) { match request_path { Some(request_path) => { if (prefix != "*") && (prefix != request_path) { return false; } } None => return false, } } true } // ANCHOR: unit-tests #[test] fn test_matches_without_wildcard() { assert!(prefix_matches("/v1/publishers", "/v1/publishers")); assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc-123")); assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc/books")); assert!(!prefix_matches("/v1/publishers", "/v1")); assert!(!prefix_matches("/v1/publishers", "/v1/publishersBooks")); assert!(!prefix_matches("/v1/publishers", "/v1/parent/publishers")); } #[test] fn test_matches_with_wildcard() { assert!(prefix_matches( "/v1/publishers/*/books", "/v1/publishers/foo/books" )); assert!(prefix_matches( "/v1/publishers/*/books", "/v1/publishers/bar/books" )); assert!(prefix_matches( "/v1/publishers/*/books", "/v1/publishers/foo/books/book1" )); assert!(!prefix_matches("/v1/publishers/*/books", "/v1/publishers")); assert!(!prefix_matches( "/v1/publishers/*/books", "/v1/publishers/foo/booksByAuthor" )); } // ANCHOR_END: unit-tests }
Day 3 Morning Exercise
A Simple GUI Library
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: setup pub trait Widget { /// Natural width of `self`. fn width(&self) -> usize; /// Draw the widget into a buffer. fn draw_into(&self, buffer: &mut dyn std::fmt::Write); /// Draw the widget on standard output. fn draw(&self) { let mut buffer = String::new(); self.draw_into(&mut buffer); println!("{}", &buffer); } } pub struct Label { label: String, } impl Label { fn new(label: &str) -> Label { Label { label: label.to_owned(), } } } pub struct Button { label: Label, callback: Box<dyn FnMut()>, } impl Button { fn new(label: &str, callback: Box<dyn FnMut()>) -> Button { Button { label: Label::new(label), callback, } } } pub struct Window { title: String, widgets: Vec<Box<dyn Widget>>, } impl Window { fn new(title: &str) -> Window { Window { title: title.to_owned(), widgets: Vec::new(), } } fn add_widget(&mut self, widget: Box<dyn Widget>) { self.widgets.push(widget); } } // ANCHOR_END: setup // ANCHOR: Window-width impl Widget for Window { fn width(&self) -> usize { // ANCHOR_END: Window-width std::cmp::max( self.title.chars().count(), self.widgets.iter().map(|w| w.width()).max().unwrap_or(0), ) } // ANCHOR: Window-draw_into fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { // ANCHOR_END: Window-draw_into let mut inner = String::new(); for widget in &self.widgets { widget.draw_into(&mut inner); } let window_width = self.width(); // TODO: after learning about error handling, you can change // draw_into to return Result<(), std::fmt::Error>. Then use // the ?-operator here instead of .unwrap(). writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap(); writeln!(buffer, "| {:^window_width$} |", &self.title).unwrap(); writeln!(buffer, "+={:=<window_width$}=+", "").unwrap(); for line in inner.lines() { writeln!(buffer, "| {:window_width$} |", line).unwrap(); } writeln!(buffer, "+-{:-<window_width$}-+", "").unwrap(); } } // ANCHOR: Button-width impl Widget for Button { fn width(&self) -> usize { // ANCHOR_END: Button-width self.label.width() + 8 // add a bit of padding } // ANCHOR: Button-draw_into fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { // ANCHOR_END: Button-draw_into let width = self.width(); let mut label = String::new(); self.label.draw_into(&mut label); writeln!(buffer, "+{:-<width$}+", "").unwrap(); for line in label.lines() { writeln!(buffer, "|{:^width$}|", &line).unwrap(); } writeln!(buffer, "+{:-<width$}+", "").unwrap(); } } // ANCHOR: Label-width impl Widget for Label { fn width(&self) -> usize { // ANCHOR_END: Label-width self.label .lines() .map(|line| line.chars().count()) .max() .unwrap_or(0) } // ANCHOR: Label-draw_into fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { // ANCHOR_END: Label-draw_into writeln!(buffer, "{}", &self.label).unwrap(); } } // ANCHOR: main fn main() { let mut window = Window::new("Rust GUI Demo 1.23"); window.add_widget(Box::new(Label::new("This is a small text GUI demo."))); window.add_widget(Box::new(Button::new( "Click me!", Box::new(|| println!("You clicked the button!")), ))); window.draw(); } // ANCHOR_END: main
Day 3 Afternoon Exercises
Safe FFI Wrapper
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: ffi mod ffi { use std::os::raw::{c_char, c_int, c_long, c_ulong, c_ushort}; // Opaque type. See https://doc.rust-lang.org/nomicon/ffi.html. #[repr(C)] pub struct DIR { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } // Layout as per readdir(3) and definitions in /usr/include/x86_64-linux-gnu. #[repr(C)] pub struct dirent { pub d_ino: c_long, pub d_off: c_ulong, pub d_reclen: c_ushort, pub d_type: c_char, pub d_name: [c_char; 256], } extern "C" { pub fn opendir(s: *const c_char) -> *mut DIR; pub fn readdir(s: *mut DIR) -> *const dirent; pub fn closedir(s: *mut DIR) -> c_int; } } use std::ffi::{CStr, CString, OsStr, OsString}; use std::os::unix::ffi::OsStrExt; #[derive(Debug)] struct DirectoryIterator { path: CString, dir: *mut ffi::DIR, } // ANCHOR_END: ffi // ANCHOR: DirectoryIterator impl DirectoryIterator { fn new(path: &str) -> Result<DirectoryIterator, String> { // Call opendir and return a Ok value if that worked, // otherwise return Err with a message. // ANCHOR_END: DirectoryIterator let path = CString::new(path).map_err(|err| format!("Invalid path: {err}"))?; // SAFETY: path.as_ptr() cannot be NULL. let dir = unsafe { ffi::opendir(path.as_ptr()) }; if dir.is_null() { Err(format!("Could not open {:?}", path)) } else { Ok(DirectoryIterator { path, dir }) } } } // ANCHOR: Iterator impl Iterator for DirectoryIterator { type Item = OsString; fn next(&mut self) -> Option<OsString> { // Keep calling readdir until we get a NULL pointer back. // ANCHOR_END: Iterator // SAFETY: self.dir is never NULL. let dirent = unsafe { ffi::readdir(self.dir) }; if dirent.is_null() { // We have reached the end of the directory. return None; } // SAFETY: dirent is not NULL and dirent.d_name is NUL // terminated. let d_name = unsafe { CStr::from_ptr((*dirent).d_name.as_ptr()) }; let os_str = OsStr::from_bytes(d_name.to_bytes()); Some(os_str.to_owned()) } } // ANCHOR: Drop impl Drop for DirectoryIterator { fn drop(&mut self) { // Call closedir as needed. // ANCHOR_END: Drop if !self.dir.is_null() { // SAFETY: self.dir is not NULL. if unsafe { ffi::closedir(self.dir) } != 0 { panic!("Could not close {:?}", self.path); } } } } // ANCHOR: main fn main() -> Result<(), String> { let iter = DirectoryIterator::new(".")?; println!("files: {:#?}", iter.collect::<Vec<_>>()); Ok(()) } // ANCHOR_END: main
Day 4 Morning Exercise
Dining Philosophers
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ANCHOR: Philosopher use std::sync::mpsc; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; struct Fork; struct Philosopher { name: String, // ANCHOR_END: Philosopher left_fork: Arc<Mutex<Fork>>, right_fork: Arc<Mutex<Fork>>, thoughts: mpsc::SyncSender<String>, } // ANCHOR: Philosopher-think impl Philosopher { fn think(&self) { self.thoughts .send(format!("Eureka! {} has a new idea!", &self.name)) .unwrap(); } // ANCHOR_END: Philosopher-think // ANCHOR: Philosopher-eat fn eat(&self) { // ANCHOR_END: Philosopher-eat println!("{} is trying to eat", &self.name); let left = self.left_fork.lock().unwrap(); let right = self.right_fork.lock().unwrap(); // ANCHOR: Philosopher-eat-end println!("{} is eating...", &self.name); thread::sleep(Duration::from_millis(10)); } } static PHILOSOPHERS: &[&str] = &["Socrates", "Plato", "Aristotle", "Thales", "Pythagoras"]; fn main() { // ANCHOR_END: Philosopher-eat-end let (tx, rx) = mpsc::sync_channel(10); let forks = (0..PHILOSOPHERS.len()) .map(|_| Arc::new(Mutex::new(Fork))) .collect::<Vec<_>>(); for i in 0..forks.len() { let tx = tx.clone(); let mut left_fork = forks[i].clone(); let mut right_fork = forks[(i + 1) % forks.len()].clone(); // To avoid a deadlock, we have to break the symmetry // somewhere. This will swap the forks without deinitializing // either of them. if i == forks.len() - 1 { std::mem::swap(&mut left_fork, &mut right_fork); } let philosopher = Philosopher { name: PHILOSOPHERS[i].to_string(), thoughts: tx, left_fork, right_fork, }; thread::spawn(move || { for _ in 0..100 { philosopher.eat(); philosopher.think(); } }); } drop(tx); for thought in rx { println!("{}", thought); } }