当前位置:网站首页>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 .
边栏推荐
- Don't want teachers to see themselves with cameras in online classes? Virtual camera you deserve!
- Extension of flutter
- Shell 实现文件基本操作(切割、排序、去重)
- LeedCode1480.一维数组的动态和
- About the practice topic of screen related to unity screen, unity moves around a certain point inside
- An excellent orm in dotnet circle -- FreeSQL
- [MCU project training] eight way answering machine
- [IELTS reading] Wang Xiwei reading P1 (reading judgment question)
- NC50528 滑动窗口
- Bypass AV with golang
猜你喜欢

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

Why is the website slow to open?

Which software can translate an English paper in its entirety?

Introduction of UART, RS232, RS485, I2C and SPI

kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)

Rust字符串切片、结构体和枚举类

AttributeError: ‘tuple‘ object has no attribute ‘layer‘问题解决

Automated defect analysis in electronic microscopic images

Detailed explanation of pod life cycle

logback配置文件
随机推荐
Introduction of UART, RS232, RS485, I2C and SPI
LeedCode1480.一维数组的动态和
Go自定义排序
[Luogu p4320] road meets (round square tree)
Multi process programming (III): message queue
【JetCache】JetCache的配置说明和注解属性说明
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
Wechat applet obtains the information of an element (height, width, etc.) and converts PX to rpx.
Is there a specific format for English papers?
详解用OpenCV的轮廓检测函数findContours()得到的轮廓拓扑结构(hiararchy)矩阵的意义、以及怎样用轮廓拓扑结构矩阵绘制轮廓拓扑结构图
Luogu_ P2010 [noip2016 popularization group] reply date_ Half enumeration
Install docker and use docker to install MySQL
Extension of flutter
[shutter] image component (image component introduction | image constructor | image.network constructor | image.asset constructor)
kubernetes编写yml简单入门
JSON转换工具类
One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function
【雅思阅读】王希伟阅读P2(阅读填空)
MySQL 23道经典面试吊打面试官
Nc17059 queue Q