by haberman · 7y ago · 0 comments
if (0..=10).contains(&5) {
I assume we are taking a ref to "5" (and not passing by value) because "Range" is a generic type that might be too big to want to copy (or it may not be copyable at all). But taking a reference to a number for a simple operation like this feels... weird. It makes me worry that Rust is going to be passing around pointers to some stack-allocated "5", but I hope that Rust is actually much smarter than that?Instead, this is a borrow which indicates that the callee will not mutate the argument. It makes more sense in this context.
Isn't that also the official name of the feature in Rust? Isn't &T in Rust pronounced "reference to T" and "&mut T" pronounced "mutable reference to T"? That is the impression I get from: https://doc.rust-lang.org/book/ch04-02-references-and-borrow...
Your parent is suggesting to not think of it in such a low-level way, and instead think of it as a permission. In this case, the pointer being optimized away makes more sense, as it’s not really about it being a pointer.
I’m of two minds about it, to be honest.
https://www.amazon.com/Rust-Programming-Language-Steve-Klabn...
Rust is all about ownership, and `&` means "don't free() this".
so yeah, it looks super weird, but when you stop to think about it, it's just that we are so used to integers being "special" that when we see them treated like a generic type it makes us cringe. interesting.
Edit: But in this case the reference will be optimized away anyway, because the callee function will be inlined.
Edit 2: Actually, the optimization does exist at the LLVM level, though it only applies in some cases. See my other comment:
Or is there something else going on?
https://play.rust-lang.org/?version=stable&mode=release&edit...
(see assembly output)
Edit 2: I lied: Rust doesn't perform such an optimization but LLVM does, -argpromote. But it only works if the callee is compiled in the same LLVM module as the caller (or with non-thin LTO), and is not visible outside that module. And since it has to respect pointer identity, it only works in a subset of cases.
Original post:
It arguably cannot, because you can cast the reference to a raw pointer and compare it to other pointers, though I don't think there's been a proper discussion on whether or not references are guaranteed to preserve pointer identity.
Edit 1: However, Rust's compilation model does theoretically allow the compiler to modify a function's ABI based on its implementation, at least in some cases, so it could theoretically perform the optimization only when calling functions which it knows don't care about pointer identity. That would avoid violating the aforementioned guarantee that may or may not exist, but it would be less reliable, as the compiler's analysis would inevitably lose track of some pointer values and treat them as escaping, thus potentially identity-sensitive, when they're actually not.