从类型断言的接口切片中删除元素 [英] Removing an element from a type asserted Slice of interfaces

查看:98
本文介绍了从类型断言的接口切片中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Golang中,断言一个切片后,如何能够从该切片中删除元素?

In Golang, after asserting to a slice, how is one able to remove an element from said slice?

例如,以下内容返回错误无法分配给值.([[interface {} interface]}

For example, the following returns the error cannot assign to value.([]interface {})

value.([]interface{}) = append(value.([]interface{})[:i],value.([]interface{})[i+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.

如果这确实是您想要的东西,则必须将切片指针存储在接口中,例如 * [] interface {} .这不会改变您无法更改接口中值的事实,但是由于这一次它是一个指针,因此我们不想更改指针,而是要更改 pointed 值(即切片值).

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)

输出(在游乐场上尝试):

&[0 one 3 4]

如您所见,我们删除了索引 2 上的元素,该元素为"two" ,现在在打印接口值时从结果中删除了该元素.

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.

这篇关于从类型断言的接口切片中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆