Introduction
Welcome! This is a tutorial to learn Rust by writing a ray tracer, based on the awesome book: Ray Tracing in One Weekend (opens in a new tab) by Peter Shirley, Trevor David Black, and Steve Hollasch. If you have read some Rust learning resources (e.g., The Book (opens in a new tab), Rust by Example (opens in a new tab), Comprehensive Rust (opens in a new tab), etc.), this is a good project to do.
To help you learn Rust, we adapt the original book, provide a reference implementation in Rust, and add some notes on Rust-specific features. We use smart pointers throughout the tutorial to avoid explicit lifetime annotations — you won’t learn much about Rust’s lifetimes, but this also makes the code nicer to work with.
We modify the original C++ code to be more Rust-ish and let you switch the languages with tabs interactively. If you know a bit about C++, you can compare Rust with C++. The C++ code is formatted with clang-format and linted with clang-tidy to ensure the code looks consistent and idiomatic. To facilitate comparison, we try to minimize content jumping when you switch languages.
Lastly, additional chapters are added in the appendix. You will learn how to parallelize the program with Rayon and make the rust code rustier with Option enum.
Along the way, you’ll use the following Rust features:
-
Basic syntax
-
Ownership
-
References and borrowing
-
Move and copy semantics
-
Modules, Cargo, and crates
-
Generics, traits, trait bounds, trait objects, and supertraits
-
Common traits:
Copy
,Clone
,Default
,Write
-
Operator overloading traits:
Add
,Sub
,Mul
,Div
,Neg
, etc. -
Concurrency traits:
Send
andSync
-
The
Box<T>
smart pointer to allocate memory on heap -
The
RC<T>
smart pointer to share ownership -
The
Arc<T>
smart pointer to share data between threads -
The
Option<T>
enum to safely model optional or nullable data -
Closures
-
And more …
Have fun!