3 ms·
Depends. "&mut T" does give you mutability. It just also gives you something else too: exclusivity. So the fact that it gives you mutability is not wrong. It's
by burntsushi 4y ago
Depends. "&mut T" does give you mutability. It just also gives you something else too: exclusivity. So the fact that it gives you mutability is not wrong. It's just incomplete.
If something is a misnomer here, I'd probably say pronouncing "&T" as "immutable reference" is it. But it really is not entirely wrong either. I can craft a Rust API that only exposes a "&T" and I can make it so you cannot mutate it. Or I can make it so it looks like you aren't mutating anything, but under the covers, mutation is happening.
Take "Regex" for example. All of its methods take "&self." From the perspective of users of that API, thinking of "Regex" as immutable is absolutely the correct model. You, as a user, cannot do anything to that "Regex" to mutate it directly in a way that you can observe via the API. You can't swap out its internal NFA. You can't change its capture group names. You can't change the prefilters it uses. You can't do anything other than use APIs that purportedly tell you "nothing is changing."
Under the covers, stuff is definitely changing. The regex engines need mutable space to operate. But all of that is hidden from you, and there's no way to observe those mutations from the public API. (You can technically make observations in the most strictest sense and make an inference from them that things are being mutated internally. For example, by measuring how long it takes for certain regexes to execute. The first search might be measurably slower than the second. But this is clearly not something that is an API guarantee or is something you can directly observe through the API of the regex. I only mention it for completeness, and because this is the Internet.)
With all that said, in my mind's eye, when I see "&T" do I think "immutable"? No. My internal conception of it is "shared."
- JohnFen 4y agoThank you for this. This helps. > So the fact that it gives you mutability is not wrong. It's just incomplete. I understand. It means nothing to anybody outside my head, but if I think of "&mut" as a misnomer, that will help me to remember that it's not telling me the whole story. I think the hardest part of learning any language is those little bits that are "hidden" by the syntax, so I need to find where to hang the lampshades so I remember them.