- Learning Rust
- Paul Johnson Vesa Kaihlavirta
- 353字
- 2021-07-02 23:07:16
How Rust uses memory
The memory occupied by any Rust program is split into two distinct areas: the heap and the stack. Simply put, the stack contains primitive variables, while the heap stores complex types. As with the mess on my daughter's bedroom floor, a heap can grow and grow until the available memory is exhausted. The stack is faster and simpler but may not grow without limits. Every binding in Rust is in a stack, but those bindings may refer to things in the heap, and elsewhere.
This all relates directly to the string example. The binding myName is in the stack, and refers to a literal static string, my name. That string being static means that it is somewhere in memory when the program starts. Its being static also means that it cannot be changed.
String::new, on the other hand, creates a String in the heap. It is initially empty, but may grow to fill the whole virtual memory space.
Here is an example of a growing String:
let mut myStringOne = "This is my first string ".to_owned(); let myStringTwo = "This is my second string. "; let myStringThree = "This is my final string"; myStringOne = myStringOne + myStringTwo + myStringTwo + myStringThree + myStringTwo;
One of the ways of creating Strings is to call the to_owned method on a string slice, like we have just done. There are other ways, but this is the most recommended one because it underlines the ownership issue. We'll get back to that later.
Here, the binding myStringOne starts out at 24 characters long, and would be allocated at least that size on the heap. The binding myStringOne is actually a reference to the position on the heap where myStringOne lives.
As we add to myStringOne, the size it occupies on the heap increases; however, the reference to the base position remains the same.
The lifetime and scope of a variable have to be taken into account. For example, if we define a string within part of a function, and then try and access the string outside the function, we get a compiler error.
- PHP動態網站程序設計
- Implementing Modern DevOps
- Spring Boot開發與測試實戰
- 算法基礎:打開程序設計之門
- SQL語言從入門到精通
- UML+OOPC嵌入式C語言開發精講
- Mastering Kali Linux for Web Penetration Testing
- 單片機C語言程序設計實訓100例
- The Professional ScrumMaster’s Handbook
- MySQL入門很輕松(微課超值版)
- 從0到1:HTML5 Canvas動畫開發
- ABAQUS6.14中文版有限元分析與實例詳解
- 算法秘籍
- INSTANT Apache Hive Essentials How-to
- Hadoop Blueprints