当前位置:网站首页>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 .
边栏推荐
- Understanding and application of least square method
- Bypass AV with golang
- Shell脚本基本使用
- One of the reasons why setinterval timer does not take effect in ie: the callback is the arrow function
- Multiprocess programming (II): Pipeline
- Overlay of shutter (Pop-Up)
- The most painful programming problem in 2021, adventure of code 2021 Day24
- Introduction of UART, RS232, RS485, I2C and SPI
- 在线预览Word文档
- Pageoffice - bug modification journey
猜你喜欢
An excellent orm in dotnet circle -- FreeSQL
Logback configuration file
Linux软件:如何安装Redis服务
使用jenkins之二Job
University of Oslo: Li Meng | deep reinforcement learning based on swing transformer
TypeError: Cannot read properties of undefined (reading ***)
Basic 10 of C language: array and pointer
Automated defect analysis in electron microscopic images-论文阅读笔记
AttributeError: ‘tuple‘ object has no attribute ‘layer‘问题解决
Bigder: how to deal with the bugs found in the 32/100 test if they are not bugs
随机推荐
Helm basic learning
v8
Shell implements basic file operations (cutting, sorting, and de duplication)
Nc50528 sliding window
[Luogu p4320] road meets (round square tree)
JSON转换工具类
NC50965 Largest Rectangle in a Histogram
字符设备注册常用的两种方法和步骤
Overlay of shutter (Pop-Up)
Array de duplication
Go custom sort
Shell implements basic file operations (SED edit, awk match)
What is the standard format of a 2000-3000 word essay for college students' classroom homework?
Linux Software: how to install redis service
[Chongqing Guangdong education] audio visual language reference materials of Xinyang Normal University
程序分析与优化 - 9 附录 XLA的缓冲区指派
Solution to the problem of abnormal display of PDF exported Chinese documents of confluence
setInterval定时器在ie不生效原因之一:回调的是箭头函数
奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习
Extension of flutter