Golang 的 列表 的删除元素使用 remove 函数,删除的元素不能为空,如果为空,会报异常。
Remove(e *Element) interface{}
参数 | 描述 |
---|---|
e | 要删除元素的列表。 |
返回被删除的元素的值。
在列表中删除元素 e,并返回被删除的元素的值。
使用 Remove 在列表中删除元素
package main
import (
"container/list"
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 Remove 在列表中删除元素
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
listHaiCoder.PushFront("HaiCoder")
element := listHaiCoder.PushFront("嗨客网")
removeEle := listHaiCoder.Remove(element)
fmt.Println("RemoveElement =", removeEle)
for i := listHaiCoder.Front(); i != nil; i = i.Next() {
fmt.Println("Element =", i.Value)
}
}
程序运行后,控制台输出如下:
我们通过 list.New 创建了一个列表 listHaiCoder,接着使用 PushFront 函数在列表中插入三个元素,接着使用 Remove 函数删除了最后插入的元素。
最后,我们打印被删除的元素和删除后的列表,Remove 函数返回的是被删除的元素的值,同时,我们发现最后插入的元素已经被成功从列表删除了。
使用 Remove 在列表中删除空元素,报错
package main
import (
"container/list"
"fmt"
)
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用 Remove 在列表中删除空元素,报错
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
listHaiCoder.PushFront("HaiCoder")
listHaiCoder.Remove(nil)
}
程序运行后,控制台输出如下:
我们使用 Remove 函数删除列表中的 nil 元素,程序直接报错。
Golang 的列表的删除元素使用 remove 函数,删除的元素不能为空,如果为空,会报异常。列表删除元素Remove 语法:
Remove(e *Element) interface{}