rust-lang / nomicon

The Dark Arts of Advanced and Unsafe Rust Programming
https://doc.rust-lang.org/nomicon/
Apache License 2.0
1.75k stars 256 forks source link

clerify dot operator mechanism of example clone #405

Closed clatisus closed 1 year ago

clatisus commented 1 year ago

The following sentences,

Consider the following more complicated example of the dot operator at work:

fn do_stuff<T: Clone>(value: &T) {
    let cloned = value.clone();
}

What type is cloned? First, the compiler checks if it can call by value. The type of value is &T, and so the clone function has signature fn clone(&T) -> T. It knows that T: Clone, so the compiler finds that cloned: T.

I believe are mis-written because the actually called clone is from type T's implementation. And according to the sections above, it's not called by value (which is type &T), but called by it's dereferencing type (which is type T).

The updated version should be something like:

What type is cloned? First, the compiler checks if it can call by value. The type of value is &T, the compiler checks if &T implements Clone (it turns out it does, as in code), but the method has wrong type (fn clone(&&T) -> &T). Then, the compiler checks & &T and &mut &T, however those method signatures also do not fit.

Finally the compile checks the deferencing type of &T, which is T. It knows that T: Clone, and the method has a correct type (fn clone(&T) -> T), so the compiler finds that cloned: T.