Home  >  Article  >  Backend Development  >  Remove element method not working in Golang

Remove element method not working in Golang

WBOY
WBOYforward
2024-02-09 09:33:181059browse

删除元素方法在 Golang 中不起作用

php editor Banana will introduce you to the method of deleting elements in Golang. In Golang, the way to delete elements is not as straightforward as in other programming languages, but we can achieve it with some tricks. In this article, we will explore several common methods to help you easily delete elements in Golang and improve programming efficiency. Whether you are a beginner or an experienced developer, these methods will help you. Let’s find out together!

Question content

I have a simple code for removing elements from a slice:

package main

import "fmt"

func main() {
    values := []string{"1", "2", "3", "4", "5"}
    valuesresult := removeelementbyindex(values2, 0)
    fmt.printf("%v - %v\n", values, valuesresult)
}

func removeelementbyindex[t interface{}](a []t, i int) []t {
    return append(a[:i], a[i+1:]...)
}

But the output is

[2 3 4 5 5] - [2 3 4 5]

For some reason values is changing but I'm not changing it in my method (I guess). Please help me fix this

Workaround

You did change the original slice. If the result of the append operation fits within the capacity of the slice, the append operation will use the original slice.

If you need the original slice unchanged:

func removeElementByIndex[T interface{}](a []T, i int) []T {
    result := make([]T, len(a)-1)
    copy(result,a[:i])
    copy(result[i:],a[i+1:])
    return result
}

The above is the detailed content of Remove element method not working in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete