C++ to Rust Cheat-Sheet

10 hours ago 1
Immutable Variable Declaration let x: i32 = 5; (immutable by default) const int x = 5; Mutable Variables let mut x = 5; int x = 5; (mutable by default) Type Inference let x = 5; auto x = 5; Constant Declaration const MAX: i32 = 100; constexpr int MAX = 100; or
consteval int MAX_FN() { return 100; } Function Declaration fn add(first: i32, second: i32) -> i32 { first + second } int add(int first, int second) { return first + second; } Implicit Return fn add(a: i32, b: i32) -> i32 { a + b } auto add(int a, int b) -> int { return a + b; } Immutable Reference &T const T& Mutable Reference &mut T T& Raw Pointer *const T
*mut T const T*
T* Struct Declaration struct Person { id: u32, health: i32 } struct Person { unsigned int id; int health; }; Struct Initialization Person { id: uid, health: 100 } Person{uid, 100} or Person{.id = uid, .health = 100}
(multiple initialization styles available in C++) Struct Field Access person.id person.id Class/Method Implementation impl MyClass { fn new(name: &String, data: &Vec) -> Self { // ... } } // Usually split between header (.h) and implementation (.cpp) // Header: class MyClass { public: MyClass(const string& name, const vector& data); }; // Implementation: MyClass::MyClass(const string& name, const vector& data) { // ... } Method with Self fn get_name(&self) -> String { self.name.clone() } string get_name() const { return name; // 'this' is implicit in C++ } Static Method fn static_method() { /* ... */ } static void static_method() { /* ... */ }
Note: 'static' in C++ has multiple meanings including file-scope lifetime, class-level function, and non-exported symbols Interface/Trait trait Shape { fn get_area(&self) -> f64; } class Shape { public: virtual double get_area() const = 0; }; Implementing Interface impl Shape for Circle { fn get_area(&self) -> f64 { // ... } } class Circle : public Shape { public: double get_area() const override { // ... } }; Generic Function fn generic_call(gen_shape: &T) { // ... } template void generic_call(const T& gen_shape) { // ... } Associated Types trait Shape { type InnerType; fn make_inner(&self) -> Self::InnerType; } // C++20 concepts approach template concept Shape = requires(T t) { typename T::InnerType; { t.make_inner() } -> std::convertible_to; }; Enums (Tagged Union) enum MyShape { Circle(f64), Rectangle(f64, f64) } // Must specify contained types std::variant my_shape; // Uses integer tags rather than named variants Pattern Matching match shape { MyShape::Circle(r) => // ..., MyShape::Rectangle(w, h) => // ... } std::visit(overloaded { [](const Circle& c) { /* ... */ }, [](const Rectangle& r) { /* ... */ } }, my_shape); Optional Types Option<T> (Some(T) or None) std::optional<T> Error Handling Result<T, E> (Ok(T) or Err(E)) std::expected<T, E> (C++23) Error Propagation let file = File::open("file.txt")?; No direct equivalent; uses exceptions or return codes Automatic Trait Implementation #[derive(Debug, Clone, PartialEq)] No direct equivalent (may change with C++26 reflection) Memory Management // Manual allocation let boxed = Box::new(value); // Explicit non-trivial copies let s = String::from("text"); let owned = borrowed.to_owned(); let cloned = original.clone(); // Manual allocation auto* ptr = new T(); // Smart pointers auto unique = std::make_unique(); auto shared = std::make_shared(); // Implicit non-trivial copies when passing by value auto copy = original; // May implicitly copy Destructors impl Drop for MyType { fn drop(&mut self) { // cleanup } } ~MyType() { // cleanup } Serialization #[derive(Serialize, Deserialize)] Requires manual implementation or code generation
(may change with C++26 reflection) Print to Console println!("Hello, {name}"); std::cout << "Hello, " << name << std::endl;
std::println("Hello, {}", name); (C++23) Debug Output println!("{:?}", object); No direct equivalent; requires custom implementation Pretty Debug Output println!("{:#?}", object); No direct equivalent
Read Entire Article