Skip to content

Commit 91b7201

Browse files
committed
Rollup merge of rust-lang#25898 - azerupi:patch-3, r=steveklabnik
As mentioned in rust-lang#25893 the copy trait is not very well explained for beginners. There is no clear mention that all primitive types implement the copy trait and there are not a lot of examples. With this change I try to make it more visible and understandable for new users. I myself have struggled with this, see [my question on stackoverflow](http://stackoverflow.com/questions/30540419/why-are-booleans-copyable-even-though-the-documentation-doesnt-indicate-that). And I want to make it more transparent for others. I filed issue rust-lang#25893 but I thought that I could give it a shot myself to relieve some of the work from the devs :) If it is not well written or there are some changes to be made before it can be merged, let me know. Cheers, Mathieu
2 parents 521f82e + 5efdcf2 commit 91b7201

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/doc/trpl/ownership.md

+40
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,46 @@ that, just like a move, when we assign `v` to `v2`, a copy of the data is made.
156156
But, unlike a move, we can still use `v` afterward. This is because an `i32`
157157
has no pointers to data somewhere else, copying it is a full copy.
158158

159+
All primitive types implement the `Copy` trait and their ownership is
160+
therefore not moved like one would assume, following the ´ownership rules´.
161+
To give an example, the two following snippets of code only compile because the
162+
`i32` and `bool` types implement the `Copy` trait.
163+
164+
```rust
165+
fn main() {
166+
let a = 5;
167+
168+
let _y = double(a);
169+
println!("{}", a);
170+
}
171+
172+
fn double(x: i32) -> i32 {
173+
x * 2
174+
}
175+
```
176+
177+
```rust
178+
fn main() {
179+
let a = true;
180+
181+
let _y = change_truth(a);
182+
println!("{}", a);
183+
}
184+
185+
fn change_truth(x: bool) -> bool {
186+
!x
187+
}
188+
```
189+
190+
If we would have used types that do not implement the `Copy` trait,
191+
we would have gotten a compile error because we tried to use a moved value.
192+
193+
```text
194+
error: use of moved value: `a`
195+
println!("{}", a);
196+
^
197+
```
198+
159199
We will discuss how to make your own types `Copy` in the [traits][traits]
160200
section.
161201

0 commit comments

Comments
 (0)