首页 > 其他 > 详细

go基础

时间:2018-03-08 13:27:39      阅读:138      评论:0      收藏:0      [点我收藏+]

for

  • 只有这一种循环结构
  • 初始化语句:在第一次迭代前执行
  • 条件表达式:在每次迭代前求值
  • 后置语句:在每次迭代的结尾执行

例子

sum := 0
for i:=0; i<=100; i++{
    sum += i
}

只保留条件表达式

sum := 0
i := 1

for ; i <= 100; {
    sum += i
    i++
}

无限循环

for {
}

if

  • 可以在条件表达前执行一个简短的语句
  • 该语句声明的变量作用域仅在 if 之内

例子

func square(v int) int {
    return v * v
}

func main(){
    x := 10

    if v := square(x); v < 100{
        fmt.Println("less than 100")
    }else{
        fmt.Println("great than or equal to 100")
    }
}

switch

  • Go 类似if 也可以运行一个条件表达式
  • Go 自动提供了在这些语言中每个 case 后面所需的 break 语句
  • Go 的switch 的 case 无需为常量,且取值不必为整数。
  • case 语句从上到下顺次执行,直到匹配成功时停止
  • 没有条件的 switch 同 switch true 一样

例子1

switch os := runtime.GOOS;os {
case "linux":
    fmt.Println("linux os")
case "windows":
    fmt.Println("windows os")
default:
    fmt.Println("other os")
}

例子2

v := rand.Int()

switch v%2 {
    case 0+0:
        fmt.Println("even number")
    case 0+1:
        fmt.Println("odd number")
    default:
        fmt.Println("error number")
}

例子3

t := time.Now()

switch  {
case t.Hour() < 12:
    fmt.Println("Good Morning!")
case t.Hour() < 17:
    fmt.Println("Good Afternoon")
default:
    fmt.Println("Good Evening")
}

defer

  • 推迟的函数调用会被压入一个栈中。 当外层函数返回时,被推迟的函数会按照后进先出的顺序调用。

例子

for i:=0; i < 10; i++ {
    defer fmt.Println(i)
}

go基础

原文:https://www.cnblogs.com/alin-qu/p/8527713.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!