Skip to content

proposal: $ for array length in index #16231

Closed
@zanesterling

Description

@zanesterling

Negative indexing is a common request from / point of contention for new Go programmers, and has been for nearly seven years.
(2015, 2013, 2011, 2009)
The main argument for is ease of access, while the main argument against is that it introduces risk of insidious bugs where an unintentionally negative index can drastically (and silently) change the properties of a slice.

I haven't seen any mention of how D does things, which is to make $ an alias for the length of the array/slice anywhere between brackets. For example:

auto arr = [1, 2, 3, 4, 5];
writeln(arr[0 .. $]) // [1, 2, 3, 4, 5]
writeln(arr[1 .. $ - 2]) // [2, 3]
writeln(arr[$ - 2 .. $]) // [4, 5]
writeln(arr[$ - 1]) // 5

Written in go syntax:

arr := []int{1, 2, 3, 4, 5}
fmt.Println(arr[0:$]) // [1, 2, 3, 4, 5]
fmt.Println(arr[1:$ - 2] // [2, 3]
fmt.Println(arr[$ - 2:$]) // [4, 5]
fmt.Println(arr[$ - 1]) // 5

This alias allows for pleasantly terse and readable slicing without risk of off-by-one errors causing silent errors. It also enables idiomatic single-line grabs, eg. taking the last element in a csv row: fmt.Println(strings.Split(row, ",")[$ - 1]).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions