Go: proposal: Go 2: add append variant that modifies its first argument instead of returning result

Created on 27 Feb 2019  ·  4Comments  ·  Source: golang/go

Proposal

A wrapper on the append function that can append to a slice by reference

Currently

a := []int{1,2,3}
b := []int{4,5,6}
a = append(a,b...)

fmt.Println(a)

Append(ByReference)

a := []int{1,2,3}
b := []int{4,5,6}
append(a,b...)

fmt.Println(a)

Output For Both

[1 2 3 4 5 6]

Why?

This would be ideal in a situation where a slice is passed down until reaching an append.
Currently, the append will return a slice which needs to be propagated back up and set on the original variable.

Clearly this is not ideal when you could simply append by reference and not need to pass the slice back.

Suggested Implementation

This can be achieved by creating a wrapper for the current append function which will overwrite the pointer of the original object with that of the one returned from the current append and will garbage collect the original slice.

FrozenDueToAge Go2 LanguageChange Proposal

Most helpful comment

This would change append from being a builtin but otherwise ordinary function into being an operation that implicitly takes the address of its first argument. Actually, it's even more complicated than that because presumably we would want

append(f(), 1)

to work. This would make append unlike anything else in the language, which is not a good thing.

All 4 comments

This would change append from being a builtin but otherwise ordinary function into being an operation that implicitly takes the address of its first argument. Actually, it's even more complicated than that because presumably we would want

append(f(), 1)

to work. This would make append unlike anything else in the language, which is not a good thing.

Why would that be better than something like https://play.golang.org/p/edcz_xp00kZ?

Why would that be better than something like https://play.golang.org/p/edcz_xp00kZ?

@OneOfOne this could work as well. In my mind it would be more generic and part of the standard library rather than a method on a specific slice type.

Effectively, a generic method on any slice type that wraps the standard append function in a similar fashion to your example.

It might be complicated though as this method will need to be written on a slice of type empty interface to be compatible with any type slice and then have some sort of type assertion.

If we had this for slices of builtin types, this could be a good first step and then one can extend that method for custom types through an interface

This could in principle change the behavior of existing code. And nothing else in the language works like this. We are not going to make this change.

Was this page helpful?
0 / 5 - 0 ratings