Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are booleans copyable even though the documentation doesn't indicate that?

Tags:

rust

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.
like image 658
Mathieu David Avatar asked May 29 '15 23:05

Mathieu David


1 Answers

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);
}
like image 170
fjh Avatar answered Sep 30 '22 06:09

fjh