add an element to the beginning of an array in go

To add an element to the beginning of an array, we can make use of slices in Go. Here's an example:

main.go
package main

import "fmt"

func main() {
    a := []int{2, 3, 4, 5}
    fmt.Println("Original slice:", a)

    // Adding a new element to the beginning of the slice
    a = append([]int{1}, a...)
    fmt.Println("Slice after adding an element to the beginning:", a)
}
269 chars
13 lines

In the above code, we first declare an integer slice a with some initial values. Here, we're using a slice instead of an array, as slices in Go are dynamic in nature.

Next, we use the append() function to add a new element to the beginning of the slice. We pass a new slice containing the element we want to add as the first argument, followed by the original slice using the spread operator .... The ... expands the original slice to a list of arguments that can be passed to the append() function.

Finally, we print the modified slice to the console. This will output the following:

main.go
Original slice: [2 3 4 5]
Slice after adding an element to the beginning: [1 2 3 4 5]
86 chars
3 lines

So, in summary, to add an element to the beginning of an array, we can convert it into a slice, add the element using the append() function, and then convert it back to an array if needed.

related categories

gistlibby LogSnag