One - One Code All

Blog Content

Go遍历list(列表)

Go   2018-01-17 20:25:03

遍历 list (列表) 需要搭配 Front() 函数获取头元素,遍历过程中,只要元素不为空则可继续调用 Next 函数往下遍历:

package main

import (
	"container/list"
	"fmt"
)

func main()  {
	l := list.New()

	// 头部添加字符串
	l.PushFront("abcd")

	// 尾部添加字符串
	l.PushBack("www.baidu.com")

	// 遍历
	for i := l.Front(); i != nil; i = i.Next() {
		fmt.Println(i.Value)
	}
}

注意,在 for 语句遍历中:


其中 i := l.Front() 表示初始赋值,用来获取列表的头部下标;

然后每次会循环会判断 i != nil,若等于空,则会退出循环,否则执行 i.Next()继续循环下一个元素;



上一篇:Go列表的append方法
下一篇:go语言字符串切割为数组strings.Split

The minute you think of giving up, think of the reason why you held on so long.