Pitch: Introduce `for borrow` and `for inout` to provide non-copying collection iteration

So, with borrowed iteration and copyable types, there are actually two independent questions here: whether for loops should borrow the collection by the default, and whether they should use an iteration strategy that allows them to borrow elements. For value-semantics collections — i.e. almost all of them — the source compatibility issues turn solely on whether the collection is borrowed: even if you have an owned copy of the collection, you can still get much better performance guarantees by doing a borrowing iteration.

I feel like that idea — making iteration default to borrowing elements when iterating a Collection, but still generating an owned copy of the collection — is a pretty good compromise position that preserves source compatibility while also extending pretty naturally in two directions:

  • Clients who want to eliminate the copy of the collection can always just use the borrow operator in the collection expression.
  • It's completely reasonable to default to borrowing move-only collections. In fact, this would be the same default evaluation rule as when values are passed as borrowed parameters: move-only values are borrowed, copyable values are copied and then borrowed.
8 Likes