Copy Types
Earlier we said, by default, ownership is transferred. If we don't want to use a borrow, we need to make a copy. Copy
types do this automatically. Types such as i32
implement the Copy
trait because it's just not worth the trouble of setting up a borrow. Why copy a reference to the stack when we can just copy our 32 bits to the stack?
So, for example, this works as we expect.
fn main() { let num = 3; greet(num); greet(num); } fn greet(num: i32) { println!("Hello, {}!", num); }
This is just like the following in Perl.
#!/usr/bin/env perl
use v5.28;
use warnings;
use experimental qw(signatures);
my $num = 3;
greet($num);
greet($num);
sub greet($num) {
say "Hello, $num!";
}
I didn't present a Copy
type first--- even though it is more akin to what happens in Perl--- because I wanted to stress that this is the exception, not the rule. Move semantics are the norm in Rust; Copy
types are the special case.