Learning the Basics of Rust Syntax#
This article uses the textbook "Comprehensive Rust" as learning material to quickly familiarize oneself with Rust syntax; at the same time, it reads Professor Fan Changchun's "Deep Dive into Rust" to deepen understanding.
The author previously worked in C++ development, so during the process of learning Rust, there is a subconscious comparison with C++, thinking about the differences in syntax and exploring the reasons behind these differences.
- About Shared References and Exclusive References
In Rust, it seems that developers are not given the right to use pointers like in C++, but only the concept of references (although the essence of references is pointers). References are divided into shared references and exclusive references, represented visually as &T
and &mut T
. The main difference lies in the borrowing rules.
Shared Reference (&T
): A shared reference is read-only access and cannot change the value it points to; the benefit of this is that it allows multiple borrows, making multi-threaded access relatively safe.
Exclusive Reference (&mut T
): An exclusive reference allows modification of data, but only one exclusive reference can exist, and no shared references can coexist.
These rules are enforced by the Rust compiler at compile time, ensuring memory and thread safety with the two types of references. In C++, there are const and & references, leading to four different situations.
- Two Types of Strings:
String
and&str
In Rust, there are two types of strings. String
is a UTF-8 encoded string stored on the heap with ownership; while &str
is a slice of a UTF-8 encoded string, equivalent to &[u8]
.
fn main() {
let s1: &str = "World";
let mut s2: String = String::from("Hello ");
}
In the above code, s1 is a slice of the string "World", which is a borrow; this "World" is actually stored in the program's read-only data segment. The variable s2, on the other hand, is stored on the heap, and s2 owns this string.
After seeing this design, I wondered why there is no way to allocate strings on the stack? Some local variables are only defined within a single scope; if every string literal exists in the read-only data segment, would it cause redundant memory usage?
After asking GPT, I received the following answer: 1. s1 is actually equivalent to a variable on the stack, but s1 does not need to be responsible for the string literal in the read-only area; this "World" will be handled by the system after the program ends; while the string on the heap, s2, will call the drop function to reclaim memory when s2's lifecycle ends. 2. The general conclusion is that Rust's compiler and linker perform a series of optimizations on the use of strings in the code, so there is no need to worry about this issue (specific optimizations can be searched and learned about).