If I understand correctly, currently Rust has three shared reference types:
&str. Under the hood,
&T is a pointer and
contain a pointer and a length. A function which expects a string should
have an argument of type
&String is legal but isn’t efficient,
since it adds another level of indirection to the string data.
I wondered if it may be possible to allow custom reference types. That is,
T there would be a default type
&T which is a pointer, but it will
be possible to override the default so for example
contain a pointer and a length. A method
ref would have to be implemented,
which creates a
&T from a
T (or, say, from a
Ref<T> which would be a
plain reference to
This would make the string and vector types less confusing, since there would
be no types
&str is especially
confusing, since it suggests the existence of a type
str). It would also
remove the need to write
s.as_slice() whenever you want to pass a
to a function - you would write
&s just like with any other type.
It would also make other references more efficient: currently, in order
to pass a
HashMap to a function you have to use
&HashMap, which contains
an unneeded level of indirection. It would have been more efficient to pass
the contents of the
HashMap struct as long as the borrow checker makes
sure that the data isn’t mutated. Custom reference types would make this possible.
~T was replaced with a type defined in the standard library,
perhaps so could
&[T], while reducing complexity and removing
unnecessary levels of indirection from other types.
Could this fit in Rust’s type system?