Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.Original topic: C++工程师视角下的Rust,有何不同?
If C++ has made its own efforts in memory safety, then its efforts in thread concurrency safety are not enough; Rust, on the other hand, has put in a lot of work on both memory safety and thread safety from the beginning, without sacrificing performance.
In some basic language expressions, Rust and C/C++ have some differences, which are reflected in:
(1) Variables are immutable by default (let), and to modify a variable, you need to explicitly use mutable binding (let mut);
(2) For objects that do not implement the Copy trait, binding, assignment, and non-reference passing by default use move semantics;
(3) Supports nested function definitions;
(4) Supports function expression returns (without a semicolon at the end);
(5) In the same scope, variables can be rebound (let), which is called the shadowing mechanism in Rust;
(6) Supports zero-sized structs, empty enums, and empty arrays ([T, 0]);
(7) Two types of string variables: &str is equivalent to const char* in C++, used to point to string literals; while String is equivalent to std::string in C++, supporting mutable references &mut String and immutable references &String;
(8) Basic data types implement the Copy trait, are allocated on the stack by default, and support copy semantics; while String, Vec, etc., by default, only support move semantics, and to perform deep copies, you need to explicitly call the clone function;
(9) Does not support switch & case, using match pattern matching instead;
(10) Does not support the ternary operator;
(11) Supports the ? operator, which is used to directly exit the current function and return the corresponding error Err when the called function returns an exception;
…