当问到这个问题时,这是 针对特定情况 的更好答案(我几乎不知道这是在Google搜索“ do while loop
golang”时的第一结果)。
将函数包装在for循环中:
package mainimport ( "fmt" "os")func main() { fmt.Println("Press 1 to run") fmt.Println("Press 2 to exit") for { sample() }}func sample() { var input int n, err := fmt.Scanln(&input) if n < 1 || err != nil { fmt.Println("invalid input") return } switch input { case 1: fmt.Println("hi") case 2: os.Exit(2) default: fmt.Println("def") }}甲
for没有任何声明循环相当于
while在其他类似C语言的循环。查看涵盖循环的Effective
Go文档
for。



