0
var twoDiamArr [][]int
var arr []int

// .... some code to add values to the above slices

// this works, and adds arr to the end of twoDiamArr:
twoDiamArr := append(twoDiamArr, arr)

// I expected this to add arr to the beginning of twoDiamArr, but it doesn't 
twoDiamArr := append(arr, twoDiamArr...)

How can I add arr to the beginning of twoDiamArr ?

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Gilo
  • 640
  • 3
  • 23

1 Answers1

1

The append() function expects the first argument passed to it to be the value that will be returned and everything starting from the second argument will be appended to it.

So if you pass a two-dimensional array inside append() as a first argument, you will have a two-dimensional array returned from it.

The expression append(arr, twoDiamArr...) is the opposite, because you are trying to put elements of a two-dimensional array inside another one-dimensional. As a result you have one dimensional array with all elements from two-dimensional

Instead, you can use a two-dimensional slice literal with the value you want to have as the first element. Everything spread in the second argument will be appended after it.

package main

import "fmt"

func main() {
    var twoDimensional = [][]int{{1}, {2}}
    var oneDimensional = []int{3}

    twoDimensional = append([][]int{oneDimensional}, twoDimensional...)

    fmt.Println(twoDimensional)
    // prints [[3] [1] [2]]
}
blackgreen
  • 34,072
  • 23
  • 111
  • 129
Eduard
  • 1,319
  • 6
  • 12