2022年2月5日 星期六

Go lang 學習筆記 - 7 Switch

 

```

package main


import (

        "fmt"

        "time"

)


func main() {

        i := 2

        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 weekend.")

        default:

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

        }


        t := time.Now()

        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("It's bool type")

                case int:

                        fmt.Println("It's int type")

                default:

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

                }

        }

        whatAmI(true)

        whatAmI(6)

        whatAmI("hey")

}

```

Switch 的用法跟 C 也是差不多

只是範例中多了 i.(type) 的用法來得到變數(可能也有常數)的型別(type)

執行結果:

two

It's weekday.

It's after noon

It's bool type

It's int type

Don't unknown type string

沒有留言:

張貼留言

Go lang 學習筆記 - 17 Pointers

``` package main import "fmt" func zeroval(n int) {         n = 0 } func zeroptr(n *int) {         *n = 0 } func main() {         ...