栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Go语言的控制流程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go语言的控制流程

使用if语言的程序清单如下:

package main

import(
  "fmt"
)
func main(){
  b:=true
  if b{
    fmt.Println("b is true!")
  }
}

运行结果如下:

b is true!

使用else语句的代码清单如下:

package main

import(
  "fmt"
)
func main(){
  b:=false
  if b{
    fmt.Println("b is true!")
  } else{
    fmt.Println("b is false!")
  }
}

运行结果如下:

b is false!

使用else if语句的程序清单如下:

package main

import(
  "fmt"
)
func main(){
  i:=2
  if i==3{
    fmt.Println("i is 3")
  } else if i==2{
    fmt.Println("i is 2")
  }
}

运行结果如下:

i is 2

使用switch语句的程序清单:

package main

import(
  "fmt"
)
func main(){
  i:=2
  switch i{
  case 2:
    fmt.Println("Two")
  case 3:
    fmt.Println("Three")
  case 4:
    fmt.Println("Four")
  }
}

运行结果如下:

Two

在switch语句中添加default case的程序清单:

package main

import(
  "fmt"
)
func main(){
  s:="c"
  switch s{
  case "a":
    fmt.Println("The letter a!")
  case "b":
    fmt.Println("The letter b!")
  default:
    fmt.Println("I don't recognize that letter!")
  }
}

运行结果如下:

I don't recognize that letter!

使用for语句进行循环的程序清单如下:

package main

import(
  "fmt"
)
func main(){
  i:=0
  for i<10{
    i++
    fmt.Println("i is",i)
  }
}

运行结果如下:

i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9
i is 10

一个包含初始化语句和后续语句的for语句的程序清单如下:

package main

import(
  "fmt"
)
func main(){
  for i:=0;i<10;i++{
    fmt.Println("i is",i)
  }
}

运行结果如下:

i is 0
i is 1
i is 2
i is 3
i is 4
i is 5
i is 6
i is 7
i is 8
i is 9

包含range子句的for语句的程序清单如下:

package main

import(
  "fmt"
)
func main(){
  numbers:=[]int{1,2,3,4}
  for i,n:= range numbers {
    fmt.Println("The index of the loop is",i)
    fmt.Println("The value from the array is",n)
  }
}

//i和n是迭代变量。i用于存储索引值,n用于存储来自数组中的值。
//迭代变量从0开始。

运行结果如下:

The index of the loop is 0
The value from the array is 1
The index of the loop is 1
The value from the array is 2
The index of the loop is 2
The value from the array is 3
The index of the loop is 3
The value from the array is 4

使用defer语句的程序清单如下:

package main

import(
  "fmt"
)
func main(){
  defer fmt.Println("I am run after the function completes")
  fmt.Println("Hello World!")
}

运行结果如下:

Hello World!
I am run after the function completes

使用多条defer语句的程序清单:

package main

import(
  "fmt"
)
func main(){
  defer fmt.Println("I am the first defer statement")
  defer fmt.Println("I am the second defer statement")
  defer fmt.Println("I am the third defer statement")
  fmt.Println("Hello World!")
}

运行结果如下:

Hello World!
I am the third defer statement
I am the second defer statement
I am the first defer statement

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/713644.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号