for 与提前退出
Coddy 面向 PHP 开发者的 Go 课程的第 10 课,共 48 课。
PHP 有 while、do/while 和 for。Go 使用 for 表示各种循环形式,没有 do/while 语句。Go 的 break 和 continue 标签不是 PHP 的数字嵌套层级。翻译嵌套循环时,要明确保留停止条件和推进路径。
for 是 Go 的循环关键字:它支持初始化/条件/更新、仅有条件,或不包含子句。break 会退出最近的循环;continue 会进入循环的下一次迭代。在循环头中声明的变量仅在该循环内有效。
PHP 示例
<?php
$n=0;
while($n<3){
++$n;
if($n===2)continue;
echo $n,"\n";
}源代码输出:
1
3Go 示例
package main
import ("fmt")
func main(){n:=8
for n>1 { n/=2 }
fmt.Println(n)}Go 输出:
1挑战
简单返回从 1 到 n(含 n)的整数之和,其中 0 <= n <= 100。
实现声明的 API,并返回结果,不要打印。驱动程序会检查必需的 API,并保留调用方输入。集合类型的标准输出使用 Go 方括号格式,而不是 JSON。
你的代码写在 exercise.go 中。main.go 存放提供的输入/输出代码,不能修改。保留一个扁平的 package main,不要再添加第二个 main。
亲手试试
package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}
func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=I(0); before0:=fmt.Sprint(a0)
result:=Solve(a0)
must(fmt.Sprint(a0)==before0,"input mutation")
fmt.Println(result)
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 PHP 开发者的 Go中的所有课
自己练习: Go 在线编译器