Home > Backend Development > Golang > How to Remove Elements from Type-Asserted Interface Slices in Go?

How to Remove Elements from Type-Asserted Interface Slices in Go?

DDD
Release: 2024-11-19 10:21:02
Original
990 people have browsed it

How to Remove Elements from Type-Asserted Interface Slices in Go?

Type Assertions in Golang: Removing Elements from Interface Slices

In Golang, type assertions allow us to extract the underlying type of an interface value. However, after type assertion, how can we manipulate the underlying value?

Consider the following example, which attempts to remove an element from a type-asserted slice of interfaces:

value := []interface{}{0, "one", "two", 3, 4}
i := 2
value.([]interface{}) = append(value.([]interface{})[:i], value.([]interface{})[i+1:]...)
Copy after login

The above code results in the error "cannot assign to value ([]interface{})". This error stems from the fact that interfaces store a copy of the underlying value, and type assertions do not modify the value within the interface.

Solution

To modify the underlying value, we must store a pointer to the slice in the interface instead. For example:

var value interface{} = &[]interface{}{0, "one", "two", 3, 4}
Copy after login

Now, we can dereference the pointer and modify the slice as follows:

sp := value.(*[]interface{})
i := 2
*sp = append((*sp)[:i], (*sp)[i+1:]...)
Copy after login

Output:

fmt.Println(value) // &[0 one 3 4]
Copy after login

As you can see, the element at index 2 ("two") has been removed from the slice. This approach successfully modifies the underlying value because the interface stores a pointer to the slice, rather than a copy of the slice itself.

The above is the detailed content of How to Remove Elements from Type-Asserted Interface Slices in Go?. For more information, please follow other related articles on the PHP Chinese website!

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