Skip to content

proposal: spec: permit conversion of []A to []B if A and B have same underlying type modulo struct tags #71183

Open
@adonovan

Description

@adonovan

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 B(a) and A(b) are legal 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.

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:

Loosely related:

@ianlancetaylor @griesemer

Metadata

Metadata

Assignees

No one assigned

    Labels

    LanguageChangeSuggested changes to the Go languageLanguageChangeReviewDiscussed by language change review committeeLanguageProposalIssues describing a requested change to the Go language specification.Proposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions