官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 海口市| 文山县| 屏东市| 莱芜市| 青龙| 光泽县| 锡林郭勒盟| 剑河县| 通城县| 桐庐县| 潜山县| 永清县| 余姚市| 阳西县| 自贡市| 六安市| 江华| 绥棱县| 白山市| 龙里县| 肥乡县| 武强县| 余江县| 兴国县| 绩溪县| 金坛市| 宽甸| 遵义县| 临漳县| 盐源县| 理塘县| 平顶山市| 乌兰浩特市| 襄城县| 宜兴市| 崇仁县| 本溪| 邳州市| 十堰市| 丹阳市| 龙里县|