当前位置:网站首页>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 .
边栏推荐
- [pulsar document] concepts and architecture
- Form form instantiation
- How SQLSEVER removes data with duplicate IDS
- 腾讯云免费SSL证书扩展文件含义
- Multiprocess programming (II): Pipeline
- [Chongqing Guangdong education] audio visual language reference materials of Xinyang Normal University
- How to write the design scheme of the thesis?
- 多进程编程(二):管道
- 数组常用操作方法整理(包含es6)及详细使用
- Why is the website slow to open?
猜你喜欢
Bloom filter
Pageoffice - bug modification journey
University of Oslo: Li Meng | deep reinforcement learning based on swing transformer
Markdown tutorial
setInterval定时器在ie不生效原因之一:回调的是箭头函数
百数不断创新,打造自由的低代码办公工具
Feature Engineering: summary of common feature transformation methods
The "2022 China Digital Office Market Research Report" can be downloaded to explain the 176.8 billion yuan market in detail
Basic use of shell script
University of Toronto:Anthony Coache | 深度强化学习的条件可诱导动态风险度量
随机推荐
What website can you find English literature on?
Markdown tutorial
布隆过滤器
[golang syntax] map common errors golang panic: assignment to entry in nil map
Shell implements basic file operations (cutting, sorting, and de duplication)
logback配置文件
Helm basic learning
Markdown使用教程
Understanding and application of least square method
如何系统学习机器学习
Where can I find foreign papers?
[shutter] image component (the placeholder | transparent_image transparent image plug-in is loaded into the memory)
Callback event after the antv X6 node is dragged onto the canvas (stepping on a big hole record)
腾讯云免费SSL证书扩展文件含义
Nacos+openfeign error reporting solution
TypeError: Cannot read properties of undefined (reading ***)
关于XML一些介绍和注意事项
Multiprocess programming (4): shared memory
[pulsar document] concepts and architecture
Luogu_ P1149 [noip2008 improvement group] matchstick equation_ Enumeration and tabulation