这是 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 }