Migration Guides

C++ to Rust Cheat-Sheet

Some people learn new programming languages best by looking at examples for how to do the same thing they know in one language is done in the other. Below is a syntax comparison table which can serve as a quick reference for common C++ constructs and their equivalents in Rust. It is not a comprehensive guide, but I hope it helps out a C++ developer looking for a quick reference to Rust syntax.

Comparing Idioms in Rust and C++

Feature Rust C++
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

Rust vs C++ Type Equivalents

Type Rust C++
Boolean bool bool
Character char (Unicode scalar value, 4 bytes) char32_t (or wchar_t on some platforms)
Byte (Raw Data) u8 (always unsigned) uint8_t or unsigned char (for guaranteed unsigned)
Unsigned Integers
u8, u16, u32, u64, u128, usize
uint8_t, uint16_t, uint32_t, uint64_t, 
__uint128, uintptr_t/size_t
Signed Integers
i8, i16, i32, i64, i128, isize
int8_t, int16_t, int32_t, int64_t, 
__int128, intptr_t/ptrdiff_t
Floating Point f32, f64 float, double
Unit Type () (unit) void
Never Type ! (never) [[noreturn]] void
Immutable Reference &T const T&
Mutable Reference &mut T T&
Raw Pointers *const T, *mut T const T*, T*
Arrays [T; N] std::array<T, N> or T[N]
Slices &[T] std::span<T> (C++20)
Dynamic Array Vec<T> std::vector<T>
String String (UTF-8 encoded) std::string
String Slice &str (UTF-8 encoded) std::string_view (C++17)
C Compatible String CString, &CStr std::string, const char*
Nullable/Optional Option<T> std::optional<T> (C++17)
Error Handling Result<T, E> std::expected<T, E> (C++23)
Smart Pointer (Unique) Box<T> std::unique_ptr<T>
Smart Pointer (Shared) Rc<T> (single-threaded)
Arc<T> (thread-safe)
std::shared_ptr<T>
Weak Pointer Weak<T> (from Rc/Arc) std::weak_ptr<T>
Hash Map HashMap<K, V> std::unordered_map<K, V>
Ordered Map BTreeMap<K, V> std::map<K, V>
Hash Set HashSet<T> std::unordered_set<T>
Ordered Set BTreeSet<T> std::set<T>
Double-Ended Queue VecDeque<T> std::deque<T>
Linked List LinkedList<T> std::list<T>
Priority Queue BinaryHeap<T> std::priority_queue<T>
Tuple (T1, T2, ...) std::tuple<T1, T2, ...>
Tagged Union enum Variant { A(T1), B(T2), ... } std::variant<T1, T2, ...> (C++17)
Interior Mutability Cell<T>, RefCell<T> mutable keyword
Thread-Safe Mutability Mutex<T>, RwLock<T> std::mutex + T
Atomic Types AtomicBool, AtomicUsize, etc. std::atomic<bool>, std::atomic<size_t>, etc.