Re:What's a reference in Rust?
by tybit on Wednesday November 29, 2017 @01:17AM
(#15804999)
So in comparison to C++ would it be correct to say that Box<T> is like unique_ptr<T>, Vec<T> is Vector<T>, and that references are the same in both languages?
[ Parent
| on HN ]
Rust's Box and Vec are analogous to C++'s unique_ptr and vector, yes. But references in Rust really aren't anything like C++ references, given that Rust references 1) are first-class, 2) come in two varieties (mutable/exclusive and immutable/shared), 3) feature mechanically-checked lifetimes, and 4) will be two words in size (rather than one) if the underlying type is dynamically-sized.
> Rust references 1) are first-class
what makes them more first-class than C++ references ? eg in C++ given a type T, you can use `std::add_lvalue_reference<T>`, `std::remove_reference<T>`, overload on references, check if a type is a reference to another...
C++ reference types are first-class. But instances of reference types are not first-class values. References are not objects, in standard speak, they do not have a memory location, you can't take their address, you can't pass them to functions (a reference parameter means passing a value by reference, not a reference by value). And so on. Rust references are more like C/C++ pointers or Java references in that they are actual values, and AFAIK Rust functions, like Java and C functions, are strictly pass-by-value.
This is a really helpful distinction, thanks for clarifying.
I think they just meant that Rust references are like normal first-class generic types. Eg, you can nest them to get a &mut &T for example, since they behave more like a pointer in that regard.
C++ references on the other hand are more like modificators of a type, eg you can have a T or a T&, but having a (T&)& does not make sense. (Outside of templates, where it gets folded down to a T&.)