GO语言系列(七)

继续前一节的示例程序。

If/Else

package main

import "fmt"

func main() {

if 7%2 == 0 {

fmt.Println("7 is even")

} else {

fmt.Println("7 is odd")

}

if 8%4 == 0 {

fmt.Println("8 is divisible by 4")

}

if num := 9; num

fmt.Println(num, "is negative")

} else if num

fmt.Println(num, "has 1 digit")

} else {

fmt.Println(num, "has multiple digits")

}

}

输出:

$ go run if-else.go

7 is odd

8 is divisible by 4

9 has 1 digit

Switch

package main

import "fmt"

import "time"

func main() {

i := 2

fmt.Print("Write ", i, " as ")

switch i {

case 1:

fmt.Println("one")

case 2:

fmt.Println("two")

case 3:

fmt.Println("three")

}

switch time.Now().Weekday() {

case time.Saturday, time.Sunday:

fmt.Println("It's the weekend")

default:

fmt.Println("It's a weekday")

}

t := time.Now()

switch {

case t.Hour()

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 an int")

default:

fmt.Printf("Don't know type %T\n", t)

}

}

whatAmI(true)

whatAmI(1)

whatAmI("hey")

}

输出:

$ go run switch.go

Write 2 as two

It's a weekday

It's after noon

I'm a bool

I'm an int

Don't know type string

数组

package main

import "fmt"

func main() {

var a [5]int

fmt.Println("emp:", a)

a[4] = 100

fmt.Println("set:", a)

fmt.Println("get:", a[4])

fmt.Println("len:", len(a))

b := [5]int

fmt.Println("dcl:", b)

var twoD [2][3]int

for i := 0; i

for j := 0; j

twoD[i][j] = i + j

}

}

fmt.Println("2d: ", twoD)

}

输出:

$ go run arrays.go

emp: [0 0 0 0 0]

set: [0 0 0 0 100]

get: 100

len: 5

dcl: [1 2 3 4 5]

2d: [[0 1 2] [1 2 3]]

发个小广告!!!走过路过,不要错过!新书来啦!!!

注:本公众号与当当店铺并无从属关系,仅为大家提供一个便捷购物地址。若有所冲突,纯属巧合,立删。

麦克叔叔每晚十点说

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180511B22OD900?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。

扫码关注云+社区

领取腾讯云代金券