Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend int to slice

I am fairly new to Go and thus my question might seem a bit naive.

I have a slice which I created using

var x []int;
for i := 2; i < 10; i += 2 {
    x = append(x, i);
}

I want to prepend an integer to this slice, something like

x = append(2, x)

but obviously it won't work since append needs a slice as the first argument.

I have tried this but it only works for strings and it's not working in my case.

like image 283
coda Avatar asked Dec 12 '18 06:12

coda


People also ask

How do you append to a slice?

Since slices are dynamically-sized, you can append elements to a slice using Golang's built-in append method. The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended.

Does append create a new slice?

The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.

How do you append to an array in go?

There is no way in Golang to directly append an array to an array. Instead, we can use slices to make it happen. The following characteristics are important to note: Arrays are of a fixed size.

Can you append a slice to a slice Golang?

append( ) function and spread operator Two slices can be concatenated using append method in the standard golang library.


2 Answers

Use a slice composite literal: []int{1}, For example:

package main  import (     "fmt" )  func main() {     var x []int     for i := 2; i < 10; i += 2 {         x = append(x, i)     }     fmt.Println(x)      x = append([]int{1}, x...)      fmt.Println(x) } 

Playground: https://play.golang.org/p/Yc87gO7gJlD

Output:

[2 4 6 8] [1 2 4 6 8] 

However, this more efficient version may make fewer allocations, An allocation is only necessary when there is no spare slice capacity.

package main  import (     "fmt" )  func main() {     var x []int     for i := 2; i < 10; i += 2 {         x = append(x, i)     }     fmt.Println(x)      x = append(x, 0)     copy(x[1:], x)     x[0] = 1      fmt.Println(x) } 

Playground: https://play.golang.org/p/fswXul_YfvD

Output:

[2 4 6 8] [1 2 4 6 8] 

Good code must be readable. In Go, we often hide implementaion details inside a function. Go compilers are optimizing compilers, small, simple functions (like prependInt) are inlined.

package main  import (     "fmt" )  func prependInt(x []int, y int) []int {     x = append(x, 0)     copy(x[1:], x)     x[0] = y     return x }  func main() {     var x []int     for i := 2; i < 10; i += 2 {         x = append(x, i)     }     fmt.Println(len(x), cap(x), x)      x = prependInt(x, 1)      fmt.Println(len(x), cap(x), x) } 

Playground: https://play.golang.org/p/wl6gvoXraKH

Output:

4 4 [2 4 6 8] 5 8 [1 2 4 6 8] 

See Go SliceTricks.

like image 116
peterSO Avatar answered Oct 07 '22 02:10

peterSO


The current version is go1.14.11

Prepend without a for loop:

package main

import "fmt"
func main () {
  data := []int{1, 2, 3, 4}
  fmt.Println(data)
  data = append([]int{99}, data...)
  fmt.Println(data)
}

Example taken form: https://codingair.wordpress.com/2014/07/18/go-appendprepend-item-into-slice/

Works with integers: https://play.golang.org/p/gaLhB5_d1Iu

like image 45
sanchezcl Avatar answered Oct 07 '22 03:10

sanchezcl