5.3. for循环语句 Go语言支持两种for循环语句,for和for…range语句。语法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | for { // Infinite loop block } for booleanExpression { // While loop block } for optionalPreStatement; booleanExpression; optionalPostStatement { block } for index, char := range aString { // String per character iteration block } for index := range aString { // String per character iteration block // char, size := utf8.DecodeRuneInString(aString[index:]) } for index, item := range anArrayOrSlice { // Array or slice iteration block } for index := range anArrayOrSlice { // Array or slice iteration block // item := anArrayOrSlice[index] } for key, value := range aMap { // Map iteration block } for key := range aMap { // Map iteration block // value := aMap[key] } for item := range aChannel { // Channel iteration block } |
大括号是必需的,但是分号只有在可选的optionalPreStatement或optionalPostStatement语句存在时才…