go语言中在一个列表上迭代元素、在[]字符串(数组)上进行迭代代码示例
一、在go语言中如何在一个列表上迭代元素?看看下面的代码将首先填充列表,
然后进行 "下一个"扫描,再进行 "上一个"扫描,以列出列表中的元素。
在列表上迭代元素示例代码:
package main
import (
"container/list"
"fmt"
)
func main() {
alist := list.New()
alist.PushBack("a")
alist.PushBack("b")
alist.PushBack("c")
fmt.Println("下一个")
for e := alist.Front(); e != nil; e = e.Next() {
// 打印出元素
fmt.Println(e.Value)
}
fmt.Println("---------")
fmt.Println("上一个")
for e := alist.Back(); e != nil; e = e.Prev() {
// 打印出元素
fmt.Println(e.Value)
}
}
输出:
下一个
a
b
c
---------
上一个
c
b
a
二、在go语言中如何在一个字符串数组中迭代,看看下面这个个简单的for循环示例,
展示了如何迭代[]string或任何种类的数组内的值。
在字符串数组中迭代示例代码:
package main
import (
"fmt"
)
func main() {
divineValues := []string{
"fearlessness",
"purification of one's existence",
"cultivation of spritual knowledge",
"charity",
"self-control",
"performance of sacrifice",
"study of the Vedas",
"austerity and simplicity",
"non-violence",
"truthfulness",
"freedom from anger",
"renunciation",
"tranquility",
"aversion to faultfinding",
"compassion and freedom from covetousness",
"gentleness",
"modesty and steady determination",
"vigor",
"forgiveness",
"fortitude",
"cleanliness",
"freedom from envy and the passion for honor",
}
for index, each := range divineValues {
fmt.Printf("Divine value [%d] is [%s]\n", index, each)
}
}
有兴趣的可以自行测试。
相关文章