当前位置:网站首页>Rust ownership (very important)
Rust ownership (very important)
2022-07-03 00:37:00 【Wang Ziqing Big Ben】
1. Memory management for other languages , stay C/C++ in , Developers need to manually release the requested memory resources . stay Java(jvm) in ,JVM Garbage collection mechanism is adopted , But this will reduce the efficiency of the runtime , Not real-time , therefore JVM Will recycle as little as possible , It's contradictory , So it's still not good , and Rust Stack memory and heap memory are treated equally , If it exceeds the scope, it will be automatically released .Rust In the case of taking into account the performance 、 It effectively reduces the amount of code and the hidden danger of memory leakage ..
2.Rust Rules of ownership : Every value has a variable , Called its owner , There can only be one owner at a time , When the owner is not within the scope of the program , This value will be deleted .
3. Variable range :rust Bounded by braces , If it is out of range, it will be recycled . When applying for memory with uncertain length , We will use the structure of heap .
4. How variables interact with data : The first is mobile (move), The second is cloning (clone).
Move (move): Multiple variables can be in Rust Interact with the same data in different ways
let x=3; let y=x;
The data here is the basic data type , So it doesn't need to be stored in the heap , Only copy and move in the stack .
Basic data type :
1. All integer types , for example i32 、 u32 、 i64 etc. .
2. Boolean type bool, The value is true or false .
3. All floating point types ,f32 and f64.
4. Character type char.
5. Tuples containing only the above types of data (Tuples).
If what happens is in the pile , It will be different :
let s1=String::from("hello");
let s2=s1;
here hello It needs to be stored in the heap , When released later , It will not be released twice , because s2=s1 when ,s1 It's no use , It cannot be used later .
clone (clone): But if you need to simply copy the data for other purposes , A second way of interacting with data can be used .
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone();
println!("s1 = {}, s2 = {}", s1, s2);
}
When resources are released here , It will be released as two resources .
5. Ownership mechanism of function
fn main() {
let s = String::from("hello");
// s Declared valid
takes_ownership(s);
// s The value of is passed into the function as a parameter
// So it can be regarded as s Has been moved , It is invalid from here
let x = 5;
// x Declared valid
makes_copy(x);
// x The value of is passed into the function as a parameter
// but x Is the basic type , Is still valid
// It can still be used here x But can't use s
} // End of the function , x Invalid , And then there was s. but s Has been moved , So don't be released
fn takes_ownership(some_string: String) {
// One String Parameters some_string Pass in , It works
println!("{}", some_string);
} // End of the function , Parameters some_string Release... Here
fn makes_copy(some_integer: i32) {
// One i32 Parameters some_integer Pass in , It works
println!("{}", some_integer);
} // End of the function , Parameters some_integer Is the basic type , No need to release
in other words , If a function variable is passed into a function as a parameter , It has the same effect as moving .
6. The ownership mechanism of function return value
fn main() {
let s1 = gives_ownership();
// gives_ownership Move its return value to s1
let s2 = String::from("hello");
// s2 Declared valid
let s3 = takes_and_gives_back(s2);
// s2 Moving as a parameter , s3 Take ownership of the return value
} // s3 Invalid is released , s2 Be moved , s1 Invalid is released .
fn gives_ownership() -> String {
let some_string = String::from("hello");
// some_string Declared valid
return some_string;
// some_string Is moved out of the function as a return value
}
fn takes_and_gives_back(a_string: String) -> String {
// a_string Declared valid
a_string // a_string Is removed from the function as a return value
}
The ownership of variables that are treated as the return value of the function will be moved out of the function , And return to the place where the function is called , And will not be released invalid .
7. quote (reference) And rent (borrow)、
A reference can actually be regarded as a pointer , Is the indirect access of variables
fn main(){
let s1=String::from("hello");
let s2=&s1;
println!("s1 is {},s2 is {}",s1,s2);
}
there s1 It will not be invalid ,s1 An address , It points to the amount in the heap ,s1 Give the address to s2,s2 Point to s1.
Remember this picture ,s2=&s1.. Of course, passing reference parameters in functions , The same effect as here .
References do not take ownership of the value , The reference is only the ownership of the leased value . After quotation s2=&s1, If s3=s1, Also is to s1 Move to s3, At this time s2 You can't rent s1 And it doesn't work , Need to rent again s3.
meanwhile , You cannot modify the value after renting , This is the same as renting a house , Without the landlord's permission , You can't change the house .
however , Or the landlord allows you to decorate :
fn main(){
let mut s1=String::from("run");
let s2=&mut s1;
s2.push_str("oob");
println!("{}",s2);
}
there &mut Decorated with variable reference types .
Put forward a very important concept : Writing memory at the same time causes data inconsistency .
Mutable references do not allow multiple references , But immutable references can .
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{}, {}", r1, r2);
There's something wrong with this code , Because multiple variable references s. and rust This design is based on the consideration of data access collision in the concurrent state , Prevent the inconsistency of data caused by writing and modifying data at the same time .
8. Overhanging quotation (dangling reference)
Definition : It refers to a pointer that does not actually point to a really accessible data ( Be careful , Not necessarily a null pointer , There may also be resources that have been released ). This is C What is said in language “ Wild pointer ”, Any pointer variable that is just created does not automatically become NULL The pointer , Its default value is random , It's going to point at all . therefore , Pointer variables should be initialized at the same time as they are created , Or set the pointer to NULL, Or let it point to legitimate memory .
stay Rust Language is not allowed , If there is , The compiler will find it .
边栏推荐
- 程序分析与优化 - 9 附录 XLA的缓冲区指派
- Where can I find the English literature of the thesis (except HowNet)?
- Extension of flutter
- Shell implements basic file operations (cutting, sorting, and de duplication)
- Nc20806 District interval
- 为什么网站打开速度慢?
- 如何系统学习机器学习
- How do educators find foreign language references?
- Luogu_ P1149 [noip2008 improvement group] matchstick equation_ Enumeration and tabulation
- [target detection] r-cnn, fast r-cnn, fast r-cnn learning
猜你喜欢

Basic 10 of C language: array and pointer

DotNet圈里一个优秀的ORM——FreeSql

Cmake basic use

可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场

How SQLSEVER removes data with duplicate IDS

Rust所有权(非常重要)

One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function

TypeError: Cannot read properties of undefined (reading ***)

pod生命周期详解
![[MCU project training] eight way answering machine](/img/a3/6a50619cd16269bf485a4a273677aa.jpg)
[MCU project training] eight way answering machine
随机推荐
One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function
【小程序项目开发-- 京东商城】uni-app之自定义搜索组件(中)-- 搜索建议
Which software can translate an English paper in its entirety?
Feature Engineering: summary of common feature transformation methods
简单聊聊运维监控的其他用途
线程的启动与优先级
redis21道经典面试题,极限拉扯面试官
NC24840 [USACO 2009 Mar S]Look Up
LeedCode1480. Dynamic sum of one-dimensional array
Thinkadmin V6 arbitrary file read vulnerability (cve-2020-25540)
免费自媒体必备工具分享
[shutter] image component (load network pictures | load static pictures | load local pictures | path | provider plug-in)
Which websites can I search for references when writing a thesis?
Where can I check the foreign literature of economics?
多进程编程(四):共享内存
Nc20806 District interval
[IELTS reading] Wang Xiwei reading P1 (reading judgment question)
Automated defect analysis in electronic microscopic images
Bloom filter
Install docker and use docker to install MySQL