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.

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 to rustc 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 update rustc and cargo 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 and rustup 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 and cargo. 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:

  1. ์˜ˆ์‹œ ๋ธ”๋ก์— ์žˆ๋Š” โ€œCopy to clipboardโ€œ๋ฒ„ํŠผ์„ ํด๋ฆญํ•ด์„œ ๋ณต์‚ฌํ•ฉ๋‹ˆ๋‹ค.
  1. Click the โ€œCopy to clipboardโ€ button on the example you want to copy.
  1. shell์—์„œ cargo new exercise๋ฅผ ์ž…๋ ฅํ•ด์„œ ์ƒˆ๋กœ์šด exercise/ ํด๋”๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.
  1. Use cargo new exercise to create a new exercise/ directory for your code:
    $ cargo new exercise
         Created binary (application) `exercise` package
  1. exercise/ ํด๋”๋กœ ์ด๋™ํ•œ ํ›„, cargo run ์ปค๋งจ๋“œ๋กœ ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค.
  1. Navigate into exercise/ and use cargo 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!
  1. ๋ณด์ผ๋Ÿฌํ”Œ๋ ˆ์ดํŠธ ์ฝ”๋“œ๋Š” src/main.rs์— ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์ด์ „ ํŽ˜์ด์ง€์˜ ์†Œ์Šค๋ฅผ ์•„๋ž˜์™€ ๊ฐ™์ด src/main.rs์— ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.
  1. Replace the boiler-plate code in src/main.rs with your own code. For example, using the example on the previous page, make src/main.rs look like
    fn main() {
        println!("Edit me!");
    }
  1. cargo run์ปค๋งจ๋“œ๋กœ ์†Œ์Šค๋ฅผ ๋นŒ๋“œํ•˜๊ณ  ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค.
  1. 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!
  1. cargo check์ปค๋งจ๋“œ๋Š” ๋น ๋ฅด๊ฒŒ ๋‹น์‹ ์˜ ํ”„๋กœ์ ํŠธ์—์„œ ์—๋Ÿฌ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • cargo build๋Š” ์‹คํ–‰์—†์ด ์†Œ์Šค๋ฅผ ์ปดํŒŒ์ผ ํ•ฉ๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ์— target/debug/ํด๋”์—์„œ output์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • cargo build --release์ปค๋งจ๋“œ๋Š” ๋ฆด๋ฆฌ์ฆˆ ๋ฒ„์ „์˜ ์ตœ์ ํ™”๋œ output์œผ๋กœ ์ปดํŒŒ์ผํ•˜๋ฉฐ target/release/ํด๋”์—์„œ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
  1. Use cargo check to quickly check your project for errors, use cargo build to compile it without running it. You will find the output in target/debug/ for a normal debug build. Use cargo build --release to produce an optimized release build in target/release/.
  1. Cargo.tomlํŒŒ์ผ์—๋Š” ๋‹น์‹ ์˜ ํ”„๋กœ์ ํŠธ์— ์‚ฌ์šฉํ•˜๋Š” ์˜์กด์„ฑ ํŒจํ‚ค์ง€๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
    • cargo์ปค๋งจ๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด ์ž๋™์œผ๋กœ ํ”„๋กœ์ ํŠธ์˜ ์˜์กด์„ฑ ํŒจํ‚ค์ง€๋ฅผ ๋‹ค์šด๋กœ๋“œ, ์ปดํŒŒ์ผ ํ•ด์ค๋‹ˆ๋‹ค.
  1. You can add dependencies for your project by editing Cargo.toml. When you run cargo 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 with i8 instead and trigger a runtime integer overflow.
  • Change let mut x to let 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 or Arc.

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 as slice::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.


์—ญ์ฃผ

1

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 and while 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, usize0, 123, 10u16
๋ถ€๋™์†Œ์ˆ˜
Floating point numbers
f32, f643.14, -10.0e20, 2f32
๋ฌธ์ž์—ด
Strings
&str"foo", r#"\\"#
์œ ๋‹ˆ์ฝ”๋“œ ๋ฌธ์ž
Unicode scalar values
char'a', 'ฮฑ', 'โˆž'
๋ฐ”์ดํŠธ ๋ฌธ์ž
Byte strings
&[u8]b"abc", br#" " "#
๋ถˆ๋ฆฌ์–ธ
Booleans
booltrue, false

๊ฐ ํƒ€์ž…์˜ ํฌ๊ธฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:

  • ์ •์ˆ˜ ๋ฐ ์†Œ์ˆ˜ํ˜•์€ ๋’ค์˜ ์ˆซ์ž์™€ ๊ฐ™์€ bits ์ž…๋‹ˆ๋‹ค.(i8=8 bit)
  • isize ์™€ usize ๋Š” ํฌ์ธํ„ฐ์™€ ๊ฐ™์€ ํฌ๊ธฐ์ž…๋‹ˆ๋‹ค.1
  • ๋ฌธ์ž๋Š” 32 bit ์ž…๋‹ˆ๋‹ค.
  • bool์€ 8 bit ์ž…๋‹ˆ๋‹ค.

The types have widths as follows:

  • iN, uN, and fN are N bits wide,
  • isize and usize are the width of a pointer,
  • char is 32 bit wide,
  • bool is 8 bit wide.

์—ญ์ฃผ

1

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> and Into<T> traits to let us convert between them. The From<T> trait has a single from() method and similarly, the Into<T> trait has a single into() 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 variable x of type i8 to an i16 by calling i16::from(x). Or, simpler, with x.into(), because From<i8> for i16 implementation automatically create an implementation of Into<i16> for i8.

  1. ์œ„ ์˜ˆ์ œ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•ด์„œ ๋ฐœ์ƒํ•œ ์˜ค๋ฅ˜๋ฅผ ํ™•์ธํ•ด ๋ณด์„ธ์š”
  2. into() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ์ˆ˜์ •ํ•˜์„ธ์š”
  3. x์™€ y๋ฅผ `f32โ€™์ด๋‚˜ โ€˜boolโ€™, โ€˜i128โ€™ ๋“ฑ์œผ๋กœ ๋ฐ”๊ฟ”์„œ ํ•ด๋‹น ํƒ€์ž…๋“ค๋กœ ๋ณ€ํ™˜์ด ๋˜๋Š”์ง€ ํ™•์ธํ•ด๋ณด์„ธ์š”
  • ์ž‘์€ ์‚ฌ์ด์ฆˆ ํƒ€์ž…์—์„œ ํฐ ์‚ฌ์ด์ฆˆ๋กœ ๋ณ€๊ฒฝํ•ด๋ณด์‹œ๊ณ  ๊ทธ ๋ฐ˜๋Œ€๋กœ๋„ ํ•ด๋ณด์„ธ์š”
  • ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋ฌธ์„œ์—์„œ ์‹œ๋„ํ•ด ๋ณธ ์ผ€์ด์Šค๊ฐ€ ๊ตฌํ˜„๋˜์–ด ์žˆ๋Š”์ง€ ํ™•์ธํ•ด ๋ณด์„ธ์š”.
  1. Execute the above program and look at the compiler error.
  2. Update the code above to use into() to do the conversion.
  3. Change the types of x and y to other things (such as f32, 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 if From<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 function transpose which will transpose a matrix (turn rows into columns):

2584567โŽค8โŽฅ9โŽฆtranspose==โŽ›โŽก1โŽœโŽข4โŽโŽฃ73โŽคโŽž6โŽฅโŽŸ9โŽฆโŽ โŽก1โŽข2โŽฃ3

๋‘ ํ•จ์ˆ˜ ๋ชจ๋‘ 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.


1

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.

์—ญ์ฃผ

1

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");
}
StackHeaps1ptrHellolen5capacity5

Manual Memory Management

์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ํ• ๋‹น, ํ•ด์ œ ํ•ฉ๋‹ˆ๋‹ค.

You allocate and deallocate heap memory yourself.

C Example

malloc๋กœ ํ• ๋‹นํ•˜๋Š” ํฌ์ธํ„ฐ๋งˆ๋‹ค free๋ฅผ ํ˜ธ์ถœํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:

You must call free on every pointer you allocate with malloc:

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 and free: 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, the std::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 after sayHello 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.


์—ญ์ฃผ

1

๋Ÿฐํƒ€์ž„์—์„œ 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 to s2 transfers ownership.
  • The data was moved from s1 and s1 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 for s2.
  • When s1 goes out of scope, nothing happens (it has been moved from).

s2์ด๋™ ์ „ ๋ฉ”๋ชจ๋ฆฌ:

Before move to s2:

StackHeaps1Rust44ํฌ์ธํ„ฐptr๊ธธ์ดlenํฌ๊ธฐcapacity

s2์ด๋™ ํ›„ ๋ฉ”๋ชจ๋ฆฌ:

After move to s2:

StackHeaps1ptrRustlen4capacity4s2ptrlen4capacity4(inaccessible)

์—ญ์ฃผ

  • ์ด๋™ ํ›„ ๋ฉ”๋ชจ๋ฆฌ ๊ทธ๋ฆผ์—์„œ 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 and s2 gets its own independent copy.
  • When s1 and s2 go out of scope, they each free their own memory.

Before copy-assignment:

StackHeaps1ptrCpplen3capacity3

After copy-assignment:

StackHeaps1ptrCpplen3capacity3s2ptrCpplen3capacity3

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 and p2 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 to struct Point?
  • Does it work when you remove Copy from the derive attribute?
  • After removing Copy, can you still print p1 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 ๋Š” as a๊ฐ€ ์œ ํšจํ•œ ๋™์•ˆ ๋นŒ๋ ค์˜จ 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 borrowed Point which is valid for at least the lifetime aโ€.
  • 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 ๋Š” as a์™€ ๋™์ผํ•œ ์ˆ˜๋ช…์„ ๊ฐ€์ง€๋Š” ๋นŒ๋ ค์˜จ 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 borrowed Point which is valid for at least the lifetime aโ€.
  • 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 and p3 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 outlives p2.

  • ์›Œํฌ์ŠคํŽ˜์ด์Šค์„ ์ดˆ๊ธฐํ™”ํ•˜๊ณ  ํ•จ์ˆ˜ ์‹œ๊ทธ๋‹ˆ์ฒ˜๋ฅผ 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์—์„œ ๋„์›Œ์ค„ํ…Œ์ง€๋งŒ ํ”Œ๋ ˆ์ด๊ทธ๋ผ์šด๋“œ์—๋Š” ๊ทธ๋Ÿฐ๊ฑฐ ์—†์Œโ€ฆ
  • ํด๋กœ์ €(์ต๋ช…ํ•จ์ˆ˜)๋ฅผ ์จ์•ผ ํ•œ๋‹ค๊ฑฐ๋‚˜ ํ•ด์„œ ๋ฌธ๋ฒ•์„ ๊ฐ„๋žตํžˆ ์“ฐ๋ฉด |param| param.item ํ˜•์‹์ž…๋‹ˆ๋‹ค.
    • js์—์„œ๋Š” param => param.item ์— ํ•ด๋‹นํ•ฉ๋‹ˆ๋‹ค.

Iterators and Ownership

๋Ÿฌ์ŠคํŠธ์˜ ์†Œ์œ ๊ถŒ ๋ชจ๋ธ์€ ๋งŽ์€ API์— ์˜ํ–ฅ์„ ์ค๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ๋“ค์–ด Iterator ์™€ IntoIterator ๊ฐ™์€ ํŠธ๋ ˆ์ดํŠธ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

The ownership model of Rust affects many APIs. An example of this is the Iterator and IntoIterator traits.

Iterator

ํŠธ๋ ˆ์ดํŠธ๋Š” ํƒ€์ž…์— ๋Œ€ํ•œ ํ–‰๋™(๋ฉ”์„œ๋“œ)๋ฅผ ์„ค๋ช…ํ•œ๋‹ค๋Š” ์ ์—์„œ ์ธํ„ฐํŽ˜์ด์Šค์™€ ์œ ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

Iterator๋Š” ๋‹จ์ˆœํžˆ None๊ฐ€ ๋‚˜์˜ฌ๋•Œ๊นŒ์ง€ next๋ฅผ ํ˜ธ์ถœํ•˜๋Š” ํŠธ๋ ˆ์ดํŠธ์ž…๋‹ˆ๋‹ค.

Traits are like interfaces: they describe behavior (methods) for a type. The Iterator trait simply says that you can call next until you get None 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 trait IntoIterator 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 as i8,
  • IntoIter: the Iterator type returned by the into_iter method. Note that IntoIter and Item are linked: the iterator must have the same Item type, which means that it returns Option<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 and IntoIterator, we can build for loops. They call into_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> and impl 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, and continue.

  • The Standard Library: String, Option and Result, Vec, HashMap, Rc and Arc.

  • 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);
}

์—ญ์ฃผ

1

๊ฐ’ ์ž์ฒด๊ฐ€ ์˜๋ฏธ๋ฅผ ๊ฐ€์ง€๋Š” ๊ฒฝ์šฐ(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);
}

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 as Box<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 the Ok 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 a User struct definition. Your goal is to implement the stubbed out methods on the User struct defined in the impl 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: ํ…Œ๋‘๋ฆฌ ๊ธธ์ด(๋‹ค๊ฐํ˜•), ๋‘˜๋ ˆ(์›)
ํžŒํŠธ- ์ฐธ์กฐํ•  ์ˆ˜์‹ํ•จ์ˆ˜ ์„ค๋ช…

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 the if 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 a while 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 a Option<i32> on every call to next(). It returns Some(x) until it is done, after which it will return None. The while 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 the while let expression. It will automatically call into_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 and continue here as usual.

loop expressions

๋งˆ์ง€๋ง‰์œผ๋กœ loopํ‚ค์›Œ๋“œ๋Š” ๋ฌดํ•œํ•œ ๋ฃจํ”„๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ๋ฐ˜๋“œ์‹œ break ๋˜๋Š” return๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋ฃจํ”„๋ฅผ ์ •์ง€ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค:

Finally, there is a loop keyword which creates an endless loop. Here you must either break or return 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 of if 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 use continue. Both continue and break 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 and Result ํƒ€์ž…: ์„ ํƒ์  ์˜ต์…˜ ๊ฐ’๊ณผ error handling์— ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.
  • String: ์†Œ์œ  ๋ฐ์ดํ„ฐ์—์„œ ์‚ฌ์šฉ๋˜๋Š” ๊ธฐ๋ณธ์ ์ธ ๋ฌธ์ž์—ด ํƒ€์ž…์ž…๋‹ˆ๋‹ค.
  • Vec: ํ™•์žฅ๊ฐ€๋Šฅํ•œ ํ‘œ์ค€ ๋ฒกํ„ฐ ํƒ€์ž…์ž…๋‹ˆ๋‹ค.
  • HashMap: ๊ตฌ์„ฑ ๊ฐ€๋Šฅํ•œ ํ•ด์‹œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ฐ€์ง€๋Š” ํ•ด์‰ฌ ๋งต ํƒ€์ž…์ž…๋‹ˆ๋‹ค
  • Box: ํž™์— ํ• ๋‹น๋œ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์†Œ์œ  ํฌ์ธํ„ฐ์ž…๋‹ˆ๋‹ค.
  • Rc: ํž™์— ํ• ๋‹น๋œ ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์ฐธ์กฐ ์นด์šดํŒ… ๊ณต์œ  ํฌ์ธํŠธ์ž…๋‹ˆ๋‹ค.
  • Option and Result 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 implements Deref<Target = str>, which means that you can call all str methods on a String.

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 implements Deref<Target = [T]>, which means that you can call slice methods on a Vec.

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.")
        }
    }
}

์—ญ์ฃผ

1

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);
}
5StackHeapfive

Box<T>์€ Deref<Target = T>๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค. ์ด๋Š” Box<T>์—์„œ T ๊ด€๋ จ ๋ฉ”์„œ๋“œ๋ฅผ ์ง์ ‘ ํ˜ธ์ถœ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์˜๋ฏธ์ž…๋‹ˆ๋‹ค.

Box<T> implements Deref<Target = T>, which means that you can call methods from T directly on a Box<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:?}");
}
StackHeaplistTagConsTagConsTagNil010211

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:

StackHeaplist0102null1/Tag1/Tag1/Tag

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 as Cell or RefCell. See Arc 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

๊ฒฝ๋กœ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ๊ตฌ๋ถ„ํ•ฉ๋‹ˆ๋‹ค:

  1. ์ƒ๋Œ€๊ฒฝ๋กœ
  • foo ๋˜๋Š” self::foo๋Š” foo๋ชจ๋“ˆ ์•ˆ์—์„œ ํ˜„์žฌ ๋ชจ๋“ˆ์„ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.
  • super::foo๋Š” foo๋ชจ๋“ˆ์˜ ๋ถ€๋ชจ ๋ชจ๋“ˆ์„ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.
  1. ์ ˆ๋Œ€ ๊ฒฝ๋กœ
  • crate::foo๋Š” ํ˜„์žฌ ํฌ๋ ˆ์ดํŠธ ๋ฃจํŠธ์˜ ์žˆ๋Š” foo๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.
  • bar::foo๋Š” barํฌ๋ ˆ์ดํŠธ ์•ˆ์— ์žˆ๋Š” foo๋ฅผ ๊ฐ€๋ฆฌํ‚ต๋‹ˆ๋‹ค.

Paths are resolved as follows:

  1. As a relative path:

    • foo or self::foo refers to foo in the current module,
    • super::foo refers to foo in the parent module.
  2. As an absolute path:

    • crate::foo refers to foo in the root of the current crate,
    • bar::foo refers to foo in the bar 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 double 3 and 1.
  • After doubling a digit, sum the digits. So doubling 7 becomes 14 which becomes 5.
  • 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 and IntoIterator used in for loops,
  • From and Into used to convert values,
  • Read and Write used for IO,
  • Add, Mul, โ€ฆ used for operator overloading, and
  • Drop 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 and Into 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 when From 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 and BufRead, you can abstract over u8 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 over u8 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 or impl 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.


์—ญ์ฃผ

1

์ œ๋„ˆ๋ฆญ๊ณผ ๊ฐ™์ด ๋Ÿฐํƒ€์ž„ ์ฝ”์ŠคํŠธ ์—†์ด ์ปดํŒŒ์ผ ์ฝ”์ŠคํŠธ๋งŒ์œผ๋กœ ๋™์ž‘ํ•˜๋Š” ์ถ”์ƒํ™” ์ปจ์…‰์ž…๋‹ˆ๋‹ค.

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:

<str as Display>::fmt<i32 as Display>::fmtStackHeapxsptrlen2capacity2Hello7b000000

๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ํŠธ๋ ˆ์ดํŠธ๋ฅผ ๊ตฌํ˜„ํ•œ ๋‹ค๋ฅธ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•  ๋•Œ๋„ ํŠธ๋ ˆ์ดํŠธ ๊ฐ์ฒด๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค:

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 a title and contains other widgets.
  • Button: has a label and a callback function which is invoked when the button is pressed.
  • Label: has a label.

The widgets will implement a Widget trait, see below.
Copy the code below to https://play.rust-lang.org/, fill in the missing draw_into methods so that you implement the Widget 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 your Cargo.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 run cargo 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 under tests/:

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, including extern 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 for CStr and CString 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 and Sync.

  • 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 later handle.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 from handle.join() to get access to the panic payload. This is a good time to talk about Any.


์—ญ์ฃผ

  • ๋‹ค๋ฅธ์–ธ์–ด์˜ ์Šค๋ ˆ๋“œ === js๋งŒ ํ–ˆ์œผ๋ฉด ํ—ฌ๊ฒŒ์ดํŠธ ์—ด๋ฆฌ๋Š” ์žฅ์ž…๋‹ˆ๋‹ค(โ€ฆ)
1

๋ฐ๋ชฌ ์Šค๋ ˆ๋“œ๋Š” ์ผ๋ฐ˜ ์Šค๋ ˆ๋“œ์˜ ๋ณด์กฐ ์Šค๋ ˆ๋“œ๋กœ ์ฃผ ์Šค๋ ˆ๋“œ๊ฐ€ ์ข…๋ฃŒ๋˜๋ฉด ๊ฐ™์ด ์ข…๋ฃŒ๋˜๊ณ , ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋‚ฎ์€ ์šฐ์„ ์ˆœ์œ„๋กœ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.

  • ๋ฐ๋ชฌ: ์‚ฌ์šฉ์ž๊ฐ€ ์ง์ ‘์ ์œผ๋กœ ์ œ์–ดํ•˜์ง€ ์•Š๊ณ  ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋™์ž‘ํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ.

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 a Receiver<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๊ฐ’์— ๋Œ€ํ•œ ์ƒํ˜ธ๋ฐฐ์ œ ์—‘์„ธ์Šค๋ฅผ ๋ณด์žฅํ•ฉ๋‹ˆ๋‹ค.
  • Arc<T>, atomic reference counted T: handled sharing between threads and takes care to deallocate T when the last thread exits,
  • Mutex<T>: ensures mutual exclusion access to the T value.

์—ญ์ฃผ

1

C++์˜ atomic์„ ๊ตฌํ˜„ํ–ˆ๋‹ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์›์ž์  ์—ฐ์‚ฐ(ํ•œ๋ฒˆ์— ์ผ์–ด๋‚˜๋Š” ๋ช…๋ น์–ด ์—ฐ์‚ฐ)์œผ๋กœ 1๊ฐœ์˜ ๋ช…๋ น์–ด๋กœ ์ฒ˜๋ฆฌํ–ˆ๋‹ค/์•ˆํ–ˆ๋‹ค๋กœ๋งŒ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.

Arc

Arc<T>๋Š” clone ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ์ฝ๊ธฐ์ „์šฉ ์ ‘๊ทผ์„ ํ—ˆ์šฉํ•ฉ๋‹ˆ๋‹ค:

Arc<T> allows shared read-only access via its clone 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 to T 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 and Mutex 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: a type T is Send if it is safe to move a T across a thread boundary.
  • Sync: a type T is Sync if it is safe to move a &T across a thread boundary.

Send

T๊ฐ€ ์Šค๋ ˆ๋“œ ๊ฐ„ ์ด๋™์ด ์•ˆ์ „ํ•˜๋‹ค๋ฉด, T์˜ ํƒ€์ž…์€ Send์ž…๋‹ˆ๋‹ค.

A type T is Send if it is safe to move a T 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 is Sync if it is safe to access a T value from multiple threads at the same time.

์ข€ ๋” ์ •ํ™•ํ•œ ์ •์˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค:

More precisely, the definition is:

&T๋งŒ Send์ธ ๊ฒฝ์šฐ, T์˜ ํƒ€์ž…์€ Sync์ž…๋‹ˆ๋‹ค.

T is Sync if and only if &T is Send

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 are Send + 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>: each Rc<T> has a reference to an RcBox<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 that cargo 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 and reqwest 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 with error: no such subcommand, then please edit the Cargo.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 the Cargo.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 TypeDescription
rust_binary๋Ÿฌ์ŠคํŠธ ๋ฐ”์ด๋„ˆ๋ฆฌ(Rust binary)๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
rust_library๋Ÿฌ์ŠคํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•˜๊ณ , rlib์™€ dylib variants๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.
rust_fficc๋ชจ๋“ˆ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Rust C library๋ฅผ ์ƒ์„ฑํ•˜๊ณ , static and shared variants๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.
rust_proc_macroproc-macro Rust library๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. ์ปดํŒŒ์ผ๋Ÿฌ ํ”Œ๋Ÿฌ๊ทธ์ธ๊ณผ ์œ ์‚ฌํ•ฉ๋‹ˆ๋‹ค.
rust_teststandard Rust test harness๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋Ÿฌ์ŠคํŠธ ํ…Œ์ŠคํŠธ ๋ฐ”์ด๋„ˆ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
rust_fuzzlibfuzzer๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋Ÿฌ์ŠคํŠธ fuzz ๋ฐ”์ด๋„ˆ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
rust_protobuf์†Œ์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ํŠน์ • protobuf์— ๋Œ€ํ•œ ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ œ๊ณตํ•˜๋Š” ๋Ÿฌ์ŠคํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
rust_bindgen์†Œ์Šค๋ฅผ ์ƒ์„ฑํ•˜๊ณ  C ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— ๋Œ€ํ•œ ๋Ÿฌ์ŠคํŠธ ๋ฐ”์ธ๋”ฉ์„ ํฌํ•จํ•˜๋Š” ๋Ÿฌ์ŠคํŠธ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค

๋‹ค์Œ์€ rust_binary์™€ rust_library๋ฅผ ์‚ดํŽด๋ด…๋‹ˆ๋‹ค.

The Android build system (Soong) supports Rust via a number of modules:

Module TypeDescription
rust_binaryProduces a Rust binary.
rust_libraryProduces a Rust library, and provides both rlib and dylib variants.
rust_ffiProduces a Rust C library usable by cc modules, and provides both static and shared variants.
rust_proc_macroProduces a proc-macro Rust library. These are analogous to compiler plugins.
rust_testProduces a Rust test binary that uses the standard Rust test harness.
rust_fuzzProduces a Rust fuzz binary leveraging libfuzzer.
rust_protobufGenerates source and produces a Rust library that provides an interface for a particular protobuf.
rust_bindgenGenerates source and produces a Rust library containing Rust bindings to C libraries.

We will look at rust_binary and rust_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 in external/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 to logcat (on-device) or stdout (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์—์„œ ๋” ๋งŽ์€ ๋Ÿฌ์ŠคํŠธ ๋ถ์„ ํ™•์ธํ•ด๋ณด์„ธ์š”.

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

(back to exercise)

// 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 from Vec<Vec<i32>> to &[&[i32]] so now you cannot easily use pretty_print either.

Day 1 Afternoon Exercises

Designing a Library

(back to exercise)

// 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

(back to exercise)

// 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

(back to exercise)

// 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

(back to exercise)

#![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

(back to exercise)

// 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

(back to exercise)

// 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

(back to exercise)

// 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);
    }
}