educative.io

Append new value to slice

suppose I have a code: var arr=make([]int,10,20)
here length of slice is 10, and capacity is 20. Now I have to add a new element at arr[10] , how can we do it?


Course: https://www.educative.io/collection/10370001/6289391964127232
Lesson: https://www.educative.io/collection/page/10370001/6289391964127232/5032337801740288

Hi @Saurav_Kumar1 !!
In Go, when you create a slice using make, the length and capacity are specified as the second and third arguments, respectively. In your example, the length of the slice arr is 10, and the capacity is 20.

If you want to add a new element to the slice at index 10, you can do so using the append function, which automatically handles resizing the slice if necessary. Here’s how you can do it:

package main

import "fmt"

func main() {
    // Create a slice with length 10 and capacity 20
    arr := make([]int, 10, 20)

    // Add elements to the slice
    for i := 0; i < 10; i++ {
        arr[i] = i + 1
    }

    fmt.Println("Original slice:", arr)

    // Add a new element at index 10
    newValue := 42
    arr = append(arr, newValue)

    fmt.Println("Updated slice:", arr)
}

In this example, we first create a slice arr with a length of 10 and a capacity of 20. We then populate the first 10 elements of the slice with values 1 to 10. Finally, we use the append function to add a new value 42 at index 10 of the slice. The append function automatically resizes the slice if needed, so you don’t have to worry about the capacity being exceeded. The resulting slice will have a length of 11 and a capacity of 20.

Please note that if you want to access the newly appended element, you would use arr[10], as slices are zero-indexed in Go.
I hope it helps. Happy Learning :blush: