Go - Remove values from a slice

发布时间 2023-10-07 23:05:11作者: ZhangZhihuiAAA

To take out the first element of the slice:

numbers   :=   [] int { 3 ,   14 ,   159 ,   26 ,   53 ,   58 } 
numbers   =   numbers [ 1 :]   //  remove  element  0

To take out the last element of the slice:

numbers   :=   [] int { 3 ,   14 ,   159 ,   26 ,   53 ,   58 } 
numbers   =   numbers [: len ( numbers ) - 1 ]   //  remove  last  element

Removing elements in between two adjacent elements within a slice is quite straightforward too. You simply append the head of the original slice with the tail of the original slice, removing whatever is in between. In this case, you want to remove the element at index 2, which is 159:

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