8

I am trying to understand the ownership and borrowing concept. At first I thought it was pretty simple once you understood it. But...

fn main() {
    let a = 5;

    let _y = double(a);
    println!("{}", a);
}

fn double(x: i32) -> i32 {
    x * 2
}

At first I would have expected this to not compile, because a would have been moved to _y.

I was a bit confused, but I found out that I would have been right except that i32 is an exception to the rule because it implements the copy trait.

I looked at the Copy trait and as I understand it, they list all types that implement this trait at the bottom.

So the bool type is not present and so I assumed it's default behaviour was to be "moved". But...

fn main() {
    let a = true;

    let _y = change_truth(a);
    println!("{}", a);
}

fn change_truth(x: bool) -> bool {
    !x
}

Doesn't fail either.

Now I am quite confused. I found the Clone trait that seems to be closely related to the copy trait. But unless I missed it, they don't really mention it in the learning doc.

Can someone give me some more info ?

Update:

  1. I have filed an issue on the Rust repository.
  2. I have also made a pull request with some change proposals.

1 Answer 1

8

Your understanding is pretty spot-on, this seems to be an issue with the docs. The documentation doesn't show Copy instances for any of the primitives types, even though they are definitely Copy. As an example to show that the compiler considers bool to be Copy, the following compiles just fine:

fn takes_copyable<T: Copy>(foo: T) {}

fn main() {
    takes_copyable(true);
}
Sign up to request clarification or add additional context in comments.

13 Comments

Oh thank you! So I do understand it correctly, that is a relief! Do all the primitive types implement the copy trait ? This should definitely be mentioned in the docs since it is a crucial exception to the most important rule in the language. If you didn't already do so, I will create an issue on github to let them know :)
Yes, I believe the primitive types should all implement Copy. And this is definitely worth filing an issue for, so go ahead.
Great thank you for your time :) The issue has been created: github.com/rust-lang/rust/issues/25893
Actually it does say in the documentation(the "Book") that all primitive types are copied by default instead of changing ownership.
@LilianA.Moraru Does it? I must have missed it. Can you give a link because it is not mentioned were I would assume it to be explained.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.