Home > Article > Backend Development > How to add a list to a list in go language
In the go language, you can use the PushFrontList() function and PushBackList() function to add a list to the list. The PushFrontList() function can insert another list at the head of the list, the syntax is "list variable.PushFrontList(list to be inserted)"; the PushBackList() function can insert another list at the end of the list, the syntax is "list variable.PushBackList(to be inserted) list of)".

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
In addition to supporting the insertion of elements, Golang's list can also insert the entire list into another list. Inserting a list into another list only supports two situations: inserting a list at the head and inserting a list at the tail.
Insert a list at the head
In Go, you can use the PushFrontList() function to insert another list at the head of the list.
Syntax
PushFrontList(other *List)
| Description | |
|---|---|
| other | #The list to insert.
Example: Use PushFrontList to insert a list at the head of the list
package main
import (
"container/list"
"fmt"
)
func main() {
//使用 PushFrontList 在列表头部插入一个列表
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
listHaiCoder.PushFront("HaiCoder")
listInsert := list.New()
listInsert.PushBack("你好")
listInsert.PushBack("hi")
listHaiCoder.PushFrontList(listInsert)
for i := listHaiCoder.Front(); i != nil; i = i.Next() {
fmt.Println("Element =", i.Value)
}
}

Insert a list at the end
In Go, you can use the PushBackList() function to insert another list at the end of the list. a list.Syntax
PushBackList(other *List)Instructions:
Example: Use PushBackList to insert a list at the end of the list
package main
import (
"container/list"
"fmt"
)
func main() {
//使用 PushBackList 在列表尾部插入一个列表
listHaiCoder := list.New()
listHaiCoder.PushFront("Hello")
listHaiCoder.PushFront("HaiCoder")
listInsert := list.New()
listInsert.PushBack("你好")
listInsert.PushBack("hi")
listHaiCoder.PushBackList(listInsert)
for i := listHaiCoder.Front(); i != nil; i = i.Next() {
fmt.Println("Element =", i.Value)
}
}

Go video tutorial、programming teaching】
The above is the detailed content of How to add a list to a list in go language. For more information, please follow other related articles on the PHP Chinese website!