Open osa1 opened 2 months ago
A variation of the second idea is we allow unboxing just one field, and generate code so that the values of the unboxing type can work as a value of the unboxed type. In the example above, this means Stack can be passed to a function that expects Vec. I.e. non-coercive subtyping, this is basically the approach some OO langs take when extending classes.
Relevant Rust RFC from 2014: RFC 223.
We should provide a way to unbox fields.
The problem we should solve is the indirections added as you "wrap" a type in other types, to add functionality.
For example, I have an immutable string type in the standard library:
and I want to implement another string type in another library that adds a memoized hash code field to the type:
This implementation will have a layer of indirection when accessing the string.
Another example would be implementing a stack using a
Vec
:Note that in this example fields of the
Vec
inarray
will change as a result of some of the operations:push
will re-allocate a new array and update theVec
's array field.Another, and very common, example is iterator types: array and array iterator, string in character iterators etc. For example:
Notes
Unboxing a type in a field is only possible if the unboxed type has no mutable fields, or the type with the unboxed field owns (i.e. initializes with the fields) the value.
As an example to the first case:
Since strings are immutable (we don't have a syntax for mutable/immutable fields yet), the
data
field will never change once initialized. SoStrIter
constructor can take aStr
argument and unbox it in itsstr
field.As an example to the second case:
Stack
can't take aVec
argument in its constructor and unbox it. The argument may be aliased, and other references to it can push elements and cause thelen
andarray
fields to change.However it can unbox the
Vec
field if it allocates it (so there are no other aliasing at the time of allocatingStack
), and we allow interior pointers so others can alias theVec
inStack
(e.g. if we provide a method that returnsself.vec
).A variation of the second idea is we allow unboxing just one field, and generate code so that the values of the unboxing type can work as a value of the unboxed type. In the example above, this means
Stack
can be passed to a function that expectsVec
. I.e. non-coercive subtyping, this is basically the approach some OO langs take when extending classes.