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

Evitar tarjeta red despierte PC wake power manager network sleep

Evitar que Windows Despierte por la Tarjeta de Red o Mantenimiento

Después de poner a la PC en modo sleep, ocurre que de repente esta arranque …

Leave a Reply

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