问题
In Golang, after asserting to a slice, how is one able to remove an element from said slice?
For example, the following returns the error cannot assign to value.([]interface {})
value.([]interface{}) = append(value.([]interface{})[:i],value.([]interface{})[i+1:]...)
回答1:
If you have a slice value wrapped in an interface, you can't change it. You can't change any value wrapped in interfaces.
When an interface value is created to wrap a value, a copy is made and stored in the interface.
When you type-assert it, you get a copy of the value, but you can't change the value in the interface. That's why it's not allowed to assign a value to it, as if it would be allowed, you would only assign a new value to a copy (that you acquire as the result of the type assertion). But the value stored in the interface would not be changed.
If this is indeed something you want, then you must store a slice pointer in the interface, e.g. *[]interface{}
. This doesn't change the fact that you can't change the value in the interface, but since this time it's a pointer, we don't want to change the pointer but the pointed value (which is the slice value).
See this example demonstrating how it works:
s := []interface{}{0, "one", "two", 3, 4}
var value interface{} = &s
// Now do the removal:
sp := value.(*[]interface{})
i := 2
*sp = append((*sp)[:i], (*sp)[i+1:]...)
fmt.Println(value)
Output (try it on the Go Playground):
&[0 one 3 4]
As you can see, we removed the element at index 2
which was "two"
which is now "gone" from the result when printing the interface value.
来源:https://stackoverflow.com/questions/47572782/removing-an-element-from-a-type-asserted-slice-of-interfaces