How do I think about references to numerical literals?
⚓ Rust 📅 2026-04-20 👤 surdeus 👁️ 4I am reading Chapter 13.2 of the Brown book and I came across Listing 13-12:
#[test]
fn iterator_demonstration() {
let v1 = vec![1, 2, 3];
let mut v1_iter = v1.iter();
assert_eq!(v1_iter.next(), Some(&1));
assert_eq!(v1_iter.next(), Some(&2));
assert_eq!(v1_iter.next(), Some(&3));
assert_eq!(v1_iter.next(), None);
}
What caught my attention is the reference to an i32 literal &1 or &2 over here. I understand references as pointers to a physical location in memory, in fact Chapter 4.2 of the Brown Book defines references as:
References are non-owning pointers, because they do not own the data they point to.
1 or 2 is data, it is not a variable, here we are not even checking assert_eq!(v1_iter.next(), Some(&v1[0]));. I can understand this working for string literals because string literals (based on my memory layout knowledge from C/C++) are stored in the data section of the memory, but I haven't heard of this happening for numerical literals, in fact, it doesn't even make sense to do so. So, what does this reference even mean theoretically?
Bonus question
: One thing which is implicit here is that if assert_eq is passed references, it dereferences them automatically, i.e.
let num1 = 42;
let num2 = 42;
let p1 = &num1;
let p2 = &num2;
assert_eq!(p1, p2); // This passes
If references truly are pointers, then this should fail, because p1 stores the address of num1 and p2 stores the address of num2, but it passes, explaining my automatic dereference claim. Then how do I assert the equality of two references which point to the same address and not the value at the respective addresses, i.e.
let num1 = 42;
let num2 = 42;
let p1 = &num1;
let p2 = &num2;
let p3 = &num1;
assert_eq!(p1, p2); // This should fail
assert_eq!(p1, p3); // This should pass
5 posts - 5 participants
🏷️ Rust_feed