Description
Background: It is not uncommon to need to convert a value of slice type []A to type []B, where A and B have the same representation (e.g. string). Unfortunately, one must allocate a copy.
Proposal: We propose to relax the restrictions so that, given var ( a A; aa []A; b B; bb []B)
, the conversion ([]B)(aa)
is legal so long as both A and B have the same underlying type, ignoring struct tags. The result would be a slice of the same len, cap, and pointer, but a different type. In other words, the operation creates an alias, it does not allocate an array.B(a)
and A(b)
are legal
The requirement for the mutual assignability same underlying type is that if aa aliases bb, then assigning to aa[0] and reading from bb[0] effects a conversion from A to B, and vice versa. Therefore both conversions had better be legal. Consequently, the two types must have the same memory layout (among other requirements).
[Edited: I mistakenly started with "mutually convertible" but this is not sufficient for e.g. A=float32 B=float64.]
Prior art:
- language: support explicit conversion from []A to []B if A is assignable to B #3756 - closed because it allowed []X->[]Y if X assignable to Y (which may change repr + allocate)
- proposal: spec: relax structural matching for conversions #19778 - similar but requires "same memory layout", which is not a spec concept
- Allow type conversion of slices of same underlying types #29864 - closed by fiat
Loosely related:
- proposal: slices: convert one slice to another #64742: generic slice conversion, requires a func(X)Y operator though.
- proposal: spec: allow assignment-compatible values in append and copy #15209: generalize append/copy to permit assignment conversions