Skip to main content

20. 控制流:循环

yaklang整合了go与python的for循环的精华,并进行了进一步的扩展。

C 风格三语句循环#

// c系的for循环for i=0;i<10;i++ {    println(i)}
/* OUTPUT:0123456789*/

Golang 风格 for-range 循环#

// golang的for-range循环遍历slice,map,channela = ["a", "b", "c", "d"]for i, v = range a {    println(i, v)}println()z = [[1, 2], [3, 4], [5, 6]]for i, j = range z {    println(i, j)}println()b = {"a": "b","c": "d","e": "f"}for k, v = range b {    println(k, v)}println()ch = make(chan int, 1)go func {        for i=0;i<4;i++ {                ch <- 1        }        close(ch)}for v = range ch {    println(v)}
/* OUTPUT:0 a1 b2 c3 d
0 [1 2]1 [3 4]2 [5 6]
a bc de f
1111*/

Golang 风格 while 循环#

在yaklang中while循环即 for 循环

i = 0sum = 0for i < 10 {    i++    sum += i}println(sum)/* OUTPUT:55*/

Python 风格 for-in 循环#

// python的for-in循环遍历slice,map,channela = ["a", "b", "c", "d"]for v in a {    println(v)}println()z = [[1, 2], [3, 4], [5, 6]]for i, j in z {    println(i, j)}println()b = {"a": "b","c": "d","e": "f"}for k in b { // 每次取key    println(k, b[k])}println()for k, v in b { // 每次取key和value    println(k, v)}println()ch = make(chan int, 1)go func {        for i=0;i<4;i++ {                ch <- 1        }        close(ch)}for v in ch {    println(v)}/* OUTPUT:0 a1 b2 c3 d
1 23 45 6
a bc de f
a bc de f
1111*/

Yak 专属 for-number#

// yak独有的for-number循环for range 4 {    println("1")}println()for i = range 4 {    println(i)}println()for in 4 {    println("1")}println()for i in 4 {    println(i)}/* OUTPUT:1111
0123
1111
0123*/

break 与 continue#

for range 4 {    println("1")    break}println()for i in 4 {    if i > 2 {            continue    }    println(i)}
/* OUTPUT:1
012*/