- 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.
- Data Visualization with D3 4.x Cookbook(Second Edition)
- LabVIEW程序設計基礎與應用
- Processing互動編程藝術
- iOS應用逆向工程(第2版)
- iOS編程基礎:Swift、Xcode和Cocoa入門指南
- Rust Essentials(Second Edition)
- C語言程序設計
- Apache Kafka Quick Start Guide
- Getting Started with Gulp
- JavaScript應用開發實踐指南
- uni-app跨平臺開發與應用從入門到實踐
- Learning Concurrency in Python
- 程序員必會的40種算法
- Python編程快速上手2
- Moodle 3.x Developer's Guide