ZhangZhihui's Blog  

There is no built-in function for insertion, but you can still use append for the task. Let’s say you want to insert the number 1000 between elements at index 2 and 3, which are ints 159 and 26, respectively:

    numbers := []int{3, 14, 159, 26, 53, 58}
    numbers = append(numbers[:2+1], numbers[2:]...)
    numbers[3] = 1000

What if you want to add an element to the beginning of the slice; for example, you want to add the integer 2000 to the beginning of the slice.

numbers = append([]int{2000}, numbers...)

What if you want to add a slice of numbers in between two elements of another slice of numbers? For example, you want to insert the slice []int{1000, 2000, 3000, 4000} in between index 2 and 3 of the numbers slice like before.

There are a few ways of doing this, but stick with using append , which is one of the shortest ways:

    numbers := []int{3, 14, 159, 26, 53, 58}
    inserted := []int{1000, 2000, 3000, 4000}

    tail := append([]int{}, numbers[3:]...)
    numbers = append(numbers[:3], inserted...)
    numbers = append(numbers, tail...)

First of all, you need to create another slice, tail , to store the tail part of the original slice. You can’t simply slice it and store it into another variable (this is called shallow copy ), because slices are not arrays: they are a pointer to a part of the array and its length. If you slice numbers and store it in tail , when you change numbers , tail will also change, and that is not what you want. Instead, you want to create a new slice by appending it to an empty slice of ints.

posted on   ZhangZhihuiAAA  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示