Go Part II: Branch statements, functions

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This is the Go second article in the series, which mainly introduces the various usages of if/else, switch and functions.

Series Finishing:

    • Go Part I: Variables, constants, and enumeration types

If you are interested in the Go language itself, you can read my translation of the advantages, disadvantages and repulsive design of the go language.

If/else

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

Switch

// 普通 switchswitch time.Now().Weekday() {    // 可以用逗号写多个值    case time.Saturday, time.Sunday:        fmt.Println("It's the weekend")    default:        fmt.Println("It's the weekday")}// 无表达式额的 switchswitch {    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")

Cycle

// 经典的循环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}

Actual test

Convert an integer to a binary representation

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

Function

// 闭包函数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, 2, 3)fmt.Println(c)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.