Remove element method not working in Golang

WBOY
Release: 2024-02-09 09:33:18
forward
1057 people have browsed it

删除元素方法在 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:]...)
}
Copy after login

But the output is

[2 3 4 5 5] - [2 3 4 5]
Copy after login

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
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!