Insertar un Elemento en un slice en GO (Golang)

package main

import (
     "fmt"
)

func main() {
     arr1 := []int{32, 57, 35, 22}
     arr2 := []int{32, 57, 35, 22}

    arr1 = append(arr1, 0)   // Making space for the new element
     copy(arr1[3:], arr1[2:]) // Shifting elements
     arr1[2] = 99             // Copying/inserting the value

    fmt.Println(arr1)        // Printing Result
    
     arr2 = append(arr2, 0)   // Making space for the new element
     insert(arr2, 99, 2)     // Another way to do it
    
     fmt.Println(arr2)        // Same result
}

func insert(array []int, element int, i int) []int {
     return append(array[:i], append([]int{element}, array[i:]...)...)
}

About AVB

Check Also

interface go golang

Qué es interface{} en GO (Golang)?

What is an interface? An interface is two things: it is a set of methods, …

Leave a Reply

Your email address will not be published. Required fields are marked *