3 ms·
Rust has affine types (can be used no more than once), but not linear types (must be used exactly once). Linear types would be a nice feature for rust, and ther
by necubi 6y ago
Rust has affine types (can be used no more than once), but not linear types (must be used exactly once). Linear types would be a nice feature for rust, and there's been some discussion about how to add them, but as far as I know there hasn't been any real progress there.
Affine types in Rust are anything with move semantics; for example you can create a method that consumes itself like this:
impl A {
fn use(&mut self) {
// takes a mutable reference to self, so it
// can be used again later
}
fn consume(self) {
// moves self into this function, which means
// it cannot be used again
}
}
- throwaway17_17 6y agoI don’t understand how a usage pattern where some variable (representing a semantic object) is said to have an affine type but it can be used more than once. Can you explain how such a type is not just a regular non-substructural type?
- necubi 6y agoSorry, that wasn't very clear. `&mut self` in the first method ("use") is an example of a non-affine type, `self` in the "consume" method is an affine type which cannot be re-used.
- atombender 6y agoWhat's the importance of having to use a value? I.e. isn't this the same as discarding it? Or is related to things like resource finalizers — i.e. once you open a file, you have to "consume" it in order for it to be closed?
- necubi 6y agoThere are lots of bugs that linear types can prevent. For example, if you have an operation that returns a Result that must be handled, you can use linear types to ensure that it is. You can also use linear types to implement safe memory management (Rust's lifetime system is basically a special case of this), by returning a value from `malloc` which must be used in a call to `free`.
- unnah 6y agoUsually what happens in Rust is that if you don't use an owned allocation, it is automatically freed. However, it is possible to leak memory by making a cycle of heap-allocated structures. Can such cycles be prevented by linear types?
- james-mcelwain 6y ago> Rust has affine types (can be used no more than once), but not linear types (must be used exactly once) Obviously it's not part of the type system itself, but doesn't the must_use attr get pretty close?