Removing an element from a type asserted Slice of interfaces

六眼飞鱼酱① 提交于 2021-02-04 19:57:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!