this post was submitted on 22 Oct 2023
6 points (87.5% liked)
Rust
7626 readers
61 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
The key thing to understand is that in Rust, references are considered unique types. This means that
&Tis a separate type fromT.So, for #1, it is not saying that
TimplementsCopy, it is saying that regardless of whatTis,&TimplementsCopy. This is because, by definition, it is always valid to copy a shared reference, even ifTitself is notCopy.Part of the reason this is confusing is that traits often include references in their function signatures; and in particular,
Clone::clonehas the signaturefn clone(&self) -> Self. So whenTimplementsclone, it has a method that takes&Tand returnsT. But even though the signature takes&T, the type that implementsCloneisTitself. (&Talways implementsCloneas well, just as it always implementsCopy, but as withCopy, this is independent from whetherTitself implementsClone. See for example the error message you get when explicitly cloning a shared reference: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a1b80cc83570321868c4ad55ee3353dc)Since
Copyis a marker trait, it doesn't have any associated methods making it explicit thatCopyaffects how&Tcan be used. However,Copyrequires the type to implementClone(even though you can implementClonein terms ofCopy) and implies thatTcan always be automatically created from&Twithout an explicit call toT::clone, so you can think of the "signature" forCopyas matching that ofClone, even though there's no actualcopymethod.For #2, I recommend thinking in terms of explicit types. Adding annotations, you get:
The type of
xisBox. You cannot assign ani32to aBox; they're different types! But the type of*xisi32, and thus you can assign84to it.The trait used to make
Boxbehave this way isDerefMut, which explicitly makes*xassignable: https://doc.rust-lang.org/std/ops/trait.DerefMut.html