This is the 24th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
In our last article, we introduced the way variables interact with data -move. We learned from the underlying principles that Rust will never automatically create a “deep copy” of data. Therefore, any automatic replication can be considered to have little impact on runtime performance.
But if we really need to make a deep copy of String data on the heap, not just on the stack, we can use a generic function called clone.
This is the second interaction between face change and data -clone
Interaction between variables and data – Clone
Take a look at the following code for a clone example:
fn main() {
let str1 = String::from("hello");
let str2 = s1.clone();
println!("str1 = {}, str2 = {}", str1, str2);
}
Copy the code
The code above does not throw an exception and explicitly produces the behavior in Figure 1, where the data on the heap is indeed copied.
A small exception should be noted, such as the following code:
fn main() {
let x = 5;
let y = x;
println!("x = {}, y = {}", x, y);
}
Copy the code
This code seems to contradict what we just learned: Clone is not called, but X is still valid and not moved into Y.
The reason is that types such as integers, whose size is known at compile time, are stored on the stack as a whole, so copying their actual value is fast. This means that there is no reason to invalidate x after creating variable y. In other words, there is no difference between shallow copy and deep copy, so the clone call will not be any different from the normal shallow copy, and we can leave it alone.
Rust has a special annotation called Copy traits, which can be used for stack-stored types such as integers (more on traits in a future article). If a type has a Copy trait, an old variable is still available after it is assigned to another variable. Rust does not allow Copy traits to be used by types that themselves or any part of them implement the Drop trait. If we use the Copy annotation for a type that requires special handling when its value leaves scope, we will get a compile-time error.
So what type is Copy? You can look at the document for a given type to confirm, but as a general rule, any combination of simple scalar values can be Copy, without allocating memory or some form of resource. Here are some types of Copy:
- All integer types, such as
u32
. - Boolean type,
bool
And its value is zerotrue
和false
. - All floating point types, such as
f64
. - Character type,
char
. - Tuples, if and only if they contain both types
Copy
From time to time. For instance,(i32, i32)
是Copy
, but(i32, String)
It is not.
conclusion
The article was first published in the wechat public account Program Yuan Xiaozhuang, at the same time in nuggets.
The code word is not easy, reprint please explain the source, pass by the little friends of the lovely little finger point like and then go (╹▽╹)