Insertar y Concatenar Elementos 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:]...)...)
}

append(s S, x ...T) S  // T is the element type of S

s0 := []int{0, 0}
s1 := append(s0, 2)        // append a single element     s1 == []int{0, 0, 2}
s2 := append(s1, 3, 5, 7)  // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
s3 := append(s2, s0...)    // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}

About AVB

Check Also

dot dot dot … tres puntos en GO (Golang), Funciones Variádicas

Para quienes vienen de otros lenguajes que no poseen funciones variádicas, esto es algo "diferente". Los ... tres puntos de go (golang) es de gran utilidad.

Leave a Reply

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