首页 > 其他分享 >Rust所有权__Ownership

Rust所有权__Ownership

时间:2024-04-14 19:24:02浏览次数:28  
标签:__ Ownership heap memory data stack Rust String

Ownership is a set of rules that govern how a Rust program manages memory. All programs have to manage the way they use a computer's memory while runing. Some languages have garbage collection that regularly looks for no-longer-used memory as the program runs;in other languages, the programmer must explicitly allocate and free the memory. Rust use a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won't complile. None of the features of ownership will slow down your program while it's runing.所有权是Rust官方用以管理内存的一系列规则,所有程序都需要在运行时使用计算机的内存。一些语言通过GC来定期回收不再使用的内存,其他语言则必须明确地分配和释放内存。Rust采取了第三种途径:由编译器根据一系列规则检查所有权来管理内存,一旦违背任何所有权规则,程序就不允许通过编译,所有权这一功能不会减缓程序的运行速度(它是在编译时执行的,与程序运行无关)   Because ownership is a new concept for many programmers, it does take some time to get use to. The good news is that the more experienced you bacome with Rust and the rules of the ownership system, the easier you'll find it to naturally develop code that is safe and efficient. Keep at it!   When you understand ownership, you'll have a solid foudation for understanding the features that make Rust unique. In this chapter, you'll learn ownership by working through some examples that focus on a very common data structure:strings.  

The Stack and the Heap   Many programming languages don't require you to think about the stack and the heap very often. But in a systems programming language like Rust, whether a value is on the stack or the heap affects how the language behaves and why you have to make certain decisions. Parts of ownership will be descibed in relation to the stack and the heap later in this chapter, so here is a brief explanation in preparation.   Both the stack and the heap are parts of memory available to your code to use at runtime, but they are stuctured in different ways. The stack stores values in the order it gets them and removes the values in the opposite order. This is referred to as last in, first out.Think of a stack of plates:when you add more plates, you put them on top of the pile, and when you need a plate, you take one off the top.Adding or removing plates from the middle or bottom wouldn't work as well! Adding data is called pushing onto the stack, and removing data is called poping off the stack. All data stored on the stack must have a known, fixed size. Data with an unknown size at compile time or a size that might change must be stored on the heap instead.   The heap is less organized: when you put data on the heap, you request a certain amount of space. The memory allocator finds an empty spot in the heap that is big enough, marks it as being in use, and returns a pointer, which is the address of that location. This process is called allocating on the heap and is sometimes abbreviated as just allocating(pushing values onto the stack is not considered allocating).Because the pointer to the heap is a known, fixed size, you can store the pointer on the stack, but when you want the actual data, you must follow the pointer. Think of being seated at a restaurant. When you enter, you state the number of people in your group, and the host finds an empty table that fits everyone and leads you there. If someone in your group comes late, they can ask where you've been seated to find you.   Pushing to the stack is faster than allocating on the heap because the allocator never has to search for a place to store new data; that location is always at the top of the stack.   Comparatively, allocating space on the heap requires more work because the allocator must first find a big enough space to hold the data and then perform bookkeeping to  prepare for the next allocation.   Accessing data in the heap is slower than accessing data on the stack because you have to follow a pointer to get there.Comtemporary processors are faster if they jump around less in memory. Continuing the analogy, consider a server at restaurant taking orders from many tables. It's most efficient to get all the orders at one table before moving on to the next table. Taking an order from table A, then an order from table B, then one from A again, and then one from B again would be a much slower process. By the same token, a  processor can do its job better if it works on data that's close to other data(as it is on the stack) rather than farther away(as it can be on the heap).    When your code calls a function, the values passed into the function(including, potentially, pointers to data on the heap) and the function's local variables get pushed  onto the stack . When the function is over, those values get poped off the stack.   Keeping track of what parts of code are using what data on the heap, minimizing the amount of duplicate data on the heap, and cleaning up unused data on heap so you  don't run out of space  are all problems that ownership addresses. Once you understand ownership, you won't need to think about the stack and the heap very often, but knowning that the main purpose of ownership is to manage heap data can help explain why it works the way it dose.   内存分为栈空间和堆空间,存储在栈空间的数据必须是已知的、固定的size,存储在堆空间的Data通常是未知size,且分配的内存空间是足够大的,并返回其内存地址(指针)给栈空间使用。
 

Ownership Rules

  First, let's take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate them:  
  • Each value in Rust has an owner.  // Rust中每个值都有所有者
  • There can only be one owner at a time. // 同一时间仅存在一个所有者(对于某个指定的值而言)
  • When the owner goes out of scope, the value will be dropped. // 当所有者超出范围,其值将被删除(占据的内存空间memory即被释放)
 

Variable Scope

  Now that we're past basic Rust syntax, we won't include all the fn main() { code in examples,  so if you're following along, make sure to put the following examples inside a main function  manually. As a result, our examples will be a bit more concise, letting us focus on the actual details rather than boilerplate code.   As a first example of ownership, we'll look at the scope of some variables. A scope is the range within a program for which an item is valid. Take the following variable:   let s = "hello";   The variable s refers to a string literal, where the value of the string is hardcoded into the text of our program. The variable is valid from the point at which it's declared until the end of the  current scope. Listing 4-1 shows a program with comments annotating where the variable s would be valid.  
    {                      // s is not valid here, it’s not yet declared
        let s = "hello";   // s is valid from this point forward

        // do stuff with s
    }                      // this scope is now over, and s is no longer valid
  In other words, there are two important points in time here:
  •  When s comes into scope, it is valid.
  •  It remains valid until it goes out of scope.
  At this point, the relationship between scopes and when variables are valid is similar to that in other programming languages. Now we'll build on top of this understanding by introducing the  String type.  

The String Type

  To illustrate the rules of ownership, we need a data type that is more complex than those we covered in the "Data Types" section of Chapter 3. The types covered previously are of a known  size, can be stored on the stack and popped off the stack when their scope is over, and can be quickly and trivially copied to make a new, independent instace if another part of code needs  to use the same value in a different scope. But we want to look at data that is stored on the heap and explore how Rusts knows when to clean up that data, and the String type is a great example.   We'll concentrate on the parts of String that relate to ownership. These aspects also apply to other complex data types, whether they are provided by the standard library or created by you. We'll discuss String in more depth in Chapter 8.   We've already seen string literals, where a string value is hardcoded into our program. String literals are convenient, but they aren't suitable for every situation in which we may want to use  text. One reason is that they're immutable. Another is that not every string value can be known when we write our code: for example, what if we want to take user input and store it? For these situations, Rust has a second string type, String. This type manages data allocated on the heap and as such is able to store an amount of text that is unknown to us at compile time. You  can create a String from a string literal using the from function, like so:   let s = String::from("hello");   The double colon :: operator allows us to namespace this particular from function under the String type rather than using some sort of name like string_from. We'll discuss this syntax  more in the "Method Syntax" section of Chapter 5, and when we talk about namespacing with modules in "Paths for Referring to an Item in the Module Tree" in Chapter 7.   This kind of string can be mutated:  
let mut s = String::from("hello");
s.push_str(", world!");
println!("{}", s); // This will print 'hello, world!'
So, what's the difference here? Why can String be mutated but literals cannot? The difference is in how these two types deal with memory.   Memory and Allocation   In the case of a string literal, we know the contents at compile time, so the text is hardcoded directly into the final executable. This is why literals are fast and efficient. But these  properties only come from the string literal's immutability. Unfortunately, we can't put a blob of memory into the binary for each piece of text whose size is unknown at compile time and  whose size might change while running the program.   With the String type, in order to support a mutable, growable piece of text, we need to allocate an amount of memory on the heap, unknown at compile time, to hold the contents. This means:  
  • The memory must be requested from the memory allocator at runtime.
  • We need a way of returning this memory to the allocator when we're done with our String.
  That first part is done by us: when we all String::from, its implementation requests the memory it needs, This is pretty much universal in programming languages.   However, the second part is different. In languages with a garbage collector(GC), the GC keeps track of and cleans up memory that isn't being used anymore, and we don't need to think about it. In most languages without a GC, it's our responsibility to identify when memory is no longer being used and to call code to explicitly free it, just as we did to request it. Doing this  correctly has historically been a difficult programming problem. If we forget, we'll waste memory.  If we do it too early, we'll have an invalid variable. If we do it twice, that's a bug too.  We need to pair wxactly one allocate with exactly one free.   Rust takes a different path: the memory is automatically returned once the variable that owns it goes out of scope. Here's a version of our scope example from Listing 4-1 using a String  instead of a string literal:  
    {
        let s = String::from("hello"); // s is valid from this point forward

        // do stuff with s
    }                                  // this scope is now over, and s is no
                                       // longer valid
  There is a natural point at which we can return the memory out String needs to the allocator: when s goes out of scope. When a variable goes out scope, Rust calls a special function for  us. This function is called drop, and it's where the author of String can put the code to return the memory. Rust call drop automatically at the closing curly bracket.   This pattern has a profound impact on the way Rust code is written. It may seem simple right now, but the behavior of code can be unexpected in more complicated situations when we  want to have multiple variables use the data we've allocated on the heap. Let's explore some of those situations now. 

标签:__,Ownership,heap,memory,data,stack,Rust,String
From: https://www.cnblogs.com/ashet/p/18134541

相关文章

  • 利用工具对特定恶意网站实行打击报复(一)
    以下内容属于纯技术记录,不存在恶意教唆他人去对非法分子实行打击报复,如造成相关利益损害,或者对受害人提供一些帮助,都与我无关,我只是想要打击报复那些广东深圳害中国人的王八蛋罢了。背景:本人因为想要试试某网站的水有多深,开始了一次小小随机的尝试,然后发现,这玩意一点也不概率,更......
  • 实验一-密码引擎-3-加密API
    实验一-密码引擎-3-加密API研究任务详情密码引擎API的主要标准和规范包括:微软的CryptoAPIRAS公司的PKCS#11标准中国商用密码标准:GMT0016-2012智能密码钥匙密码应用接口规范,GMT0018-2012密码设备应用接口规范等研究以上API接口,总结他们的异同,并以龙脉GM3000Key为例,写出......
  • 积木大赛
    转化成差分之后,差分数组里面正数的和一定不会小于负数的和的绝对值(因为\(h_i>0\)),所以答案的下界是正数的和我们来证明一定存在一种方案达到下界用数学归纳法。设差分数组为\(d\)显然\(d_1≥0\);也有\(d_1+d_2≥0\)(假设\(d_2\)为负),也就是说,我们可以通过先操作\(d_1\)和\(d_2\)来......
  • 实验一-密码引擎-3-加密API研究
    密码引擎API的主要标准和规范包括:微软的CryptoAPIRAS公司的PKCS#11标准中国商用密码标准:GMT0016-2012智能密码钥匙密码应用接口规范,GMT0018-2012密码设备应用接口规范等研究以上API接口,总结他们的异同,并以龙脉GM3000Key为例,写出调用不同接口的代码,提交博客链接和代码链......
  • 第十周
    第十周完成nginx编译安装脚本#!/bin/bashNGINX_VERSION=1.22.1NGINX_FILE=nginx-${NGINX_VERSION}.tar.gzNGINX_URL=http://nginx.org/download/NGINX_INSTALL_DIR=/apps/nginxSRC_DIR=/usr/local/srcCPUS=`lscpu|awk'/^CPU\(s\)/{print$2}'`./etc/os-rel......
  • 实验2C语言分支与循环基础应用编程
    #include<stdio.h>#include<stdlib.h>#include<time.h>#defineN5intmain(){intnumber;inti;srand(time(0));for(i=0;i<N;++i){number=rand()%65+1;printf("20238331%04d\n"......
  • 抽象代数课程笔记
    抽象代数的意义:\(\newcommand{\a}{\alpha}\newcommand{\b}{\beta}\newcommand{\D}{\Delta}\newcommand{\eps}{\varepsilon}\newcommand{\ph}{\varphi}\newcommand{\t}{\theta}\newcommand{\la}{\lambda}\newcommand{\si}{\sigma}\newcommand{\d......
  • Ubuntu下离线安装PostgreSQL
      首先,我的环境是Ubuntu20.04  如果是在线安装,根据官网的介绍很简单#安装包sudoaptupdatesudoaptinstallwgetgnupg#导入仓库sudosh-c'echo"debhttps://apt.postgresql.org/pub/repos/apt$(lsb_release-cs)-pgdgmain">/etc/apt/......
  • mv 命令 – 移动或改名文件
    语法格式:mv参数源文件名目标文件名常用参数:mv命令来自英文单词move的缩写,中文译为“移动”,其功能与英文含义相同,能够对文件进行剪切和重命名操作。这是一个被高频使用的文件管理命令,我们需要留意它与复制命令的区别。cp命令是用于文件的复制操作,文件个数是增加的,而mv......
  • RestTemplate进行https请求时适配信任证书
    转载请注明出处:1.http协议请求使用RestTemplate进行http协议的请求时,不需要考虑证书验证相关问题,以下为使用RestTemplate直接使用的代码示例:importorg.springframework.web.client.RestTemplate;importorg.springframework.http.ResponseEntity;importorg.spring......