当前位置:网站首页>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 .
边栏推荐
- Andorid gets the system title bar height
- 简单聊聊运维监控的其他用途
- 多进程编程(五):信号量
- Introduction and use of ftrace tool
- Maya fishing house modeling
- Hundreds of continuous innovation to create free low code office tools
- 关于XML一些介绍和注意事项
- Go自定义排序
- Briefly talk about other uses of operation and maintenance monitoring
- About qbytearray storage hexadecimal and hexadecimal conversion
猜你喜欢
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
可下载《2022年中国数字化办公市场研究报告》详解1768亿元市场
Basic 10 of C language: array and pointer
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
Bloom filter
[target detection] r-cnn, fast r-cnn, fast r-cnn learning
布隆过滤器
redis21道经典面试题,极限拉扯面试官
What are the recommended thesis translation software?
Understanding and application of least square method
随机推荐
DotNet圈里一个优秀的ORM——FreeSql
University of Toronto: Anthony coach | the conditions of deep reinforcement learning can induce dynamic risk measurement
The "2022 China Digital Office Market Research Report" can be downloaded to explain the 176.8 billion yuan market in detail
AcWing_ 188. Warrior cattle_ bfs
ftrace工具的介绍及使用
Multiprocess programming (4): shared memory
在线预览Word文档
Why is the website slow to open?
Attributeerror: 'tuple' object has no attribute 'layer' problem solving
About the practice topic of screen related to unity screen, unity moves around a certain point inside
JSON转换工具类
【luogu P4320】道路相遇(圆方树)
Multiprocess programming (V): semaphores
Shell 实现文件基本操作(sed-编辑、awk-匹配)
Shell implements basic file operations (SED edit, awk match)
node_ Modules cannot be deleted
What is the standard format of a 2000-3000 word essay for college students' classroom homework?
FAQ | FAQ for building applications for large screen devices
Free we media essential tools sharing
奥斯陆大学:Li Meng | 基于Swin-Transformer的深度强化学习