Go 第二部分:分支语句、函数

前端之家收集整理的这篇文章主要介绍了Go 第二部分:分支语句、函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

这是 Go 系列的第二篇文章,主要介绍 if/else,switch 和函数的各种用法

系列整理:

如果对 Go 语言本身感兴趣,可以阅读我的这篇译文 Go语言的优点,缺点和令人厌恶的设计

if/else

@H_502_16@// 声明可以先于条件,if 中的声明的变量只在此 if/else 有效 if num := 9; num < 0 { } else if num < 10 { } else { }

switch

@H_502_16@// 普通 switch switch time.Now().Weekday() { // 可以用逗号写多个值 case time.Saturday,time.Sunday: fmt.Println("It's the weekend") default: fmt.Println("It's the weekday") } // 无表达式额的 switch switch { case t.Hour() < 12: fmt.Println("It's before noon") default: fmt.Println("It's after noon") } // 比较类型 whatAmI := func(i interface{}) { switch t := i.(type) { case bool: fmt.Println("I'm a bool") case int: fmt.Println("I'm a int") default: fmt.Printf("Don't know type %T\n",t) } } whatAmI(true) whatAmI(1) whatAmI("hey")

循环

@H_502_16@// 经典的循环 for n := 0; n <= 5; n++ { if n % 2 == 0 { continue } fmt.Println(n) } // 只有条件 for i <= 3 { fmt.Println(i) i = i + 1 } // 死循环 for { fmt.Println("loop") break }

实际测试

将整数转换为二进制表示

@H_502_16@func convertToBin(v int) string { result := "" for ; v > 0; v /= 2 { result = strconv.Itoa(v % 2) + result } return result }

函数

@H_502_16@// 闭包函数 func apply(op func(int,int) int,a,b int) int { return op(a,b) } func main() { result := apply(func(i int,i2 int) int { return int(math.Pow(float64(i),float64(i2))) },2,2) fmt.Println(result) } // 可变参数 func sum(num ... int) int { var result = 0 for _,v := range num { result = result + v } return result } c := sum(1,3) fmt.Println(c)

猜你在找的Go相关文章