[Pitch] Noncopyable (or "move-only") structs and enums

It is useful to be able to write generic code that works on an arbitrary type, copyable or not. Many basic data structures and algorithms do not innately require copying values and so can naturally be generalized to work with non-copyable types. For correctness, code like that has to work generically with the type as if it were non-copyable. When given a copyable type, it effectively promises not to (locally) copy it.

From that perspective, copyability is a positive constraint, just like an ordinary protocol constraint. For example, if Array were generalized to allow non-copyable types, it would still be conditionally copyable:

extension Array: Copyable where Element: Copyable

(You might think that you could do the same with NonCopyable as a positive constraint, and in simple cases this does make sense:

extension Array: NonCopyable where Element: NonCopyable

But the basic direction of the logic is wrong, as you can see when you consider a similar generalization of Dictionary:

extension Dictionary: NonCopyable where Key: NonCopyable, Value: NonCopyable

This is wrong; it is making Dictionary non-copyable if both of the key and value types are non-copyable, but in fact Dictionary needs to be non-copyable if either argument is non-copyable. Similar logic applies to e.g. inferring non-copyability for structs. This is a clear sign that the direction of the constraint is backwards.)

13 Likes