Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

C++ to Rust cheat sheet

A quick reference: the C++ thing you reach for, its usual Rust spelling, and the chapter that explains it. When the translation is not one-to-one, the chapter is worth reading before you rely on the table.

Values and types

C++RustChapter
const auto x = 1; / auto x = 1;let x = 1; / let mut x = 1;Values and types
int, int64_t, size_t, uint8_ti32, i64, usize, u8Values and types
Implicit numeric conversionsNone: as, From, TryFromValues and types
Signed overflow is UBPanic in debug, wrap in release; wrapping_*, checked_*, saturating_*Values and types
std::array<T, N>[T; N]Values and types
std::pair, std::tuple(A, B)Values and types
struct with constructorstruct + fn new(...) -> SelfValues and types
constexpr value / functionconst / const fnValues and types
static_assert(cond)const _: () = assert!(cond);Macros
cond ? a : bif cond { a } else { b }Values and types
enum classenumEnums and match
std::variant + std::visitenum with data + matchEnums and match
std::optional<T>, nullable T*Option<T>, Option<&T>Enums and match
switchmatch (exhaustive, no fall-through)Enums and match
Structured bindingsPatterns: let (a, b) = ...;, if let, let ... elseEnums and match

Ownership and references

C++RustChapter
RAII, destructorDropOwnership
auto y = std::move(x);let y = x; (and x is unusable)Ownership
Copy constructor.clone() (Clone); implicit only for Copy typesOwnership
Rule of fiveNothing to write; add Drop if neededOwnership
const T&&T (many at once)Borrowing
T&&mut T (exclusive)Borrowing
std::span<T>, std::string_view&[T], &strBorrowing
__restrictEvery &mut TBorrowing
Iterator invalidation (UB)Compile errorBorrowing
Dangling reference (UB)Compile error; lifetimesLifetimes
Class holding a string_viewstruct View<'a> { s: &'a str }Lifetimes
std::unique_ptr<T>Box<T>Smart pointers
std::shared_ptr<T>Rc<T> (one thread), Arc<T> (atomic)Smart pointers
std::weak_ptr<T>Weak<T>, .upgrade()Smart pointers
mutable memberCell<T>, RefCell<T>Smart pointers
Object pool + raw pointersArena + generational Handle<T>Handles and arenas

Classes, templates and operators

C++RustChapter
Member function / const member functionfn f(&mut self) / fn f(&self)Borrowing
Abstract base class, virtual functionsTrait, dyn TraitTraits and generics
Template + conceptGeneric with trait boundsTraits and generics
auto f() returning a hidden typefn f() -> impl TraitTraits and generics
Nested typedef in a traits classAssociated typeTraits and generics
Inheritance of dataComposition (+ traits for behavior)Traits and generics
operator+, operator+=impl Add, impl AddAssignOperators
operator[]Index, IndexMutOperators
operator==, operator<=>#[derive(PartialEq, Eq, PartialOrd, Ord)]Operators
Converting constructorFrom / IntoOperators
operator<<(ostream&, T)impl Display, #[derive(Debug)]Operators
operator-> on a smart pointerDerefOperators
LambdaClosure (move for by-value capture)Closures and iterators
std::function<R(A)>Box<dyn Fn(A) -> R>Closures and iterators
Callable template parameterimpl Fn(A) -> R, F: FnMut(A) -> RClosures and iterators

Errors

C++RustChapter
ExceptionsResult<T, E> and ?Errors
std::expected<T, E>Result<T, E>Errors
[[nodiscard]]#[must_use] (default on Result)Errors
assert, std::terminateassert!, panic!, .expect("why")Errors
Exception class hierarchyError enum with thiserrorErrors
Catch-all handler at the topanyhow::Result with .context(...)Errors
-fno-exceptionspanic = "abort"Errors

Standard library

C++RustChapter
std::vector<T>Vec<T>Collections
v.at(i) / v[i]v.get(i) (Option) / v[i] (checked)Collections
Erase-remove idiomv.retain(keep) (keep is a closure)Collections
std::unordered_map, std::mapHashMap, BTreeMapCollections
map[key] (inserting)map.entry(key).or_default()Collections
std::stringString (always UTF-8)Collections
std::filesystem::pathPathBuf, &PathCollections
<algorithm>, rangesIterator adapters: map, filter, zip, fold, collectClosures and iterators
std::threadstd::thread::spawn, std::thread::scopeConcurrency
std::mutex next to the dataMutex<T> containing the dataConcurrency
std::atomic<T>AtomicU32 etc. with OrderingConcurrency
Thread pool / TBB parallel_forrayon: par_iter()Concurrency
std::chrono::steady_clockstd::time::Instant, DurationGame loop
Function-local staticOnceLock, LazyLockGame loop

Build, modules and tooling

C++RustChapter
CMake + vcpkg/ConanCargo + crates.ioCargo
Debug / Releasecargo build / cargo build --release (profiles)Cargo
add_subdirectoryWorkspace membersAssets and build
add_custom_commandbuild.rsAssets and build
namespacemodModules
#include "x.h"mod x; + useModules
public / privatepub / private by defaultModules
#ifdef#[cfg(...)], Cargo featuresMacros
#define macrosmacro_rules!Macros
Reflection macros, code generators#[derive(...)]Macros
GoogleTest / Catch2#[test], cargo testTesting
Google BenchmarkcriterionTesting
clang-format / clang-tidycargo fmt / cargo clippyTesting
Doxygencargo doc (examples are tested)Testing

Low level

C++RustChapter
sizeof, alignof, offsetofsize_of::<T>(), align_of::<T>(), offset_of!Memory and performance
Declaration-order layout#[repr(C)]Memory and performance
alignas(64)#[repr(align(64))]Memory and performance
Replace operator new#[global_allocator]Memory and performance
Arena / linear allocatorbumpaloHandles and arenas
T**const T, *mut T (deref in unsafe)Unsafe
Uninitialized storageMaybeUninit<T>Unsafe
reinterpret_castPointer as casts; bytemuck for safe byte viewsUnsafe
ASan / UBSanMiriUnsafe
extern "C" declarationsunsafe extern "C" { ... }FFI
Exporting a C API#[unsafe(no_mangle)] pub extern "C" fnFFI
char* stringsCStr, CString, c"..."FFI
Headers → bindingsbindgen; cbindgen for the reverseFFI
<immintrin.h>std::arch + #[target_feature]Math and SIMD
LoadLibrary / dlopenlibloadingHot reloading

Graphics and engine

C++RustChapter
GLM / DirectXMathglamMath and SIMD
memcpy a struct into a GPU bufferbytemuck::cast_slice on #[derive(Pod)] typesMath and SIMD
GLFW / SDLwinit (ApplicationHandler)Game loop
glad / GLEWgl, glowOpenGL
vulkan.h / volkashVulkan
VMAgpu-allocator, vk-memVulkan
Dawn, bgfx, sokol_gfxwgpuwgpu
openxr.h, OpenXR-Hppopenxr-sys, openxrOpenXR
glslc / dxcnaga, shaderc, from build.rswgpu
EnTT, flecshecs, bevy_ecsECS
SingletonsContext passed as a parameter; ECS resourcesGame loop
Custom serialization / reflectionserdeAssets and build
sol2 (Lua)mluaHot reloading

When the borrow checker says no

SymptomUsual fixChapter
"cannot borrow as mutable because it is also borrowed as immutable"Shorten the first borrow: copy the value out, or finish using it firstBorrowing
Pushing to a Vec while holding a reference into itHold an index instead of a referenceBorrowing
Two &mut into the same structBorrow separate fields (split borrows); destructure let S { a, b } = &mut s;ECS
Two &mut into the same slicesplit_at_mut, chunks_mut, iter_mutCollections
A struct wants to store a reference to another objectStore a handle or index; or own the dataHandles and arenas
Objects pointing at each other (graph, parent links)Arena + handles; Rc + Weak only if ownership is truly sharedECS
"borrowed value does not live long enough"Move the owner to an outer scope, or return an owned valueLifetimes
"Rc<...> cannot be sent between threads safely"Arc (and Mutex for mutation)Concurrency
A closure passed to thread::spawn borrows a localmove the data in, or use thread::scopeConcurrency
Global mutable statePass a context; or Mutex, atomics, OnceLockGame loop