- 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.
- 大話PLC(輕松動(dòng)漫版)
- VMware View Security Essentials
- Java入門經(jīng)典(第6版)
- MySQL數(shù)據(jù)庫應(yīng)用與管理 第2版
- 造個(gè)小程序:與微信一起干件正經(jīng)事兒
- Interactive Data Visualization with Python
- Web Development with Django Cookbook
- INSTANT Weka How-to
- Java:Data Science Made Easy
- Oracle 18c 必須掌握的新特性:管理與實(shí)戰(zhàn)
- C++寶典
- 快速入門與進(jìn)階:Creo 4·0全實(shí)例精講
- 邊玩邊學(xué)Scratch3.0少兒趣味編程
- Splunk Developer's Guide(Second Edition)
- Scratch超人漫游記:創(chuàng)意程序設(shè)計(jì):STEAM創(chuàng)新教育指南