Skip to content

proposal: Go 2: make final index in a three-index slice expression default to the middle index value #25638

Closed
@zigo101

Description

@zigo101

The current three-index slice form index presentation rule quite discourages gophers to use three-index slice forms. The current rule requires the middle and final index must be both represent in a three-index slice form, which makes three-index slice form quite verbose.

For example, many library may contain functions like the following one:

var hiddenOpts = []Option{...}

func NewX(opts ...Option) *X {
    opts := append(opts, hiddenOpts...)
    return createX(opts)
}

The defect (if it is not a bug) of the function NewX is it may modify the underlying data of passed arguments. It is better to use append(opts[:len(opts):len(opts)], hiddenOpts...) instead. But for its verbosity, its uses are limited.

In fact, in practice, when a three-index form is used, the final index is often same as the middle index. In particular, s[ : len(s) : len(s)] is used most often. So I propose the following simplified three-index slice forms:

s[ : n : ]  // <=> s[ : n : n]
s[m : n : ] // <=> s[m : n : n]
s[ : : ]    // <=> s[ : len(s) : len(s)]
s[m : : ]   // <=> s[m : len(s) : len(s)]

So that, we can use append(opts[::], hiddenOpts...) in the above NewX function, without too verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions