go語言中if語句用法執行個體_Golang

來源:互聯網
上載者:User

本文執行個體講述了go語言中if語句用法。分享給大家供大家參考。具體分析如下:

if 語句看起來跟 C 或者 Java 中的一樣,除了沒有了 ( ) 之外(甚至強制不能使用它們),而 { } 是必須的。

複製代碼 代碼如下:
package main
import (
    "fmt"
    "math"
)
func sqrt(x float64) string {
    if x < 0 {
        return sqrt(-x) + "i"
    }
    return fmt.Sprint(math.Sqrt(x))
}
func main() {
    fmt.Println(sqrt(2), sqrt(-4))
}

跟 for 一樣,if 語句可以在條件之前執行一個簡單的語句。

由這個語句定義的變數的範圍僅在 if 範圍之內。

(在最後的 return 語句處使用 v 看看。)

複製代碼 代碼如下:
package main
import (
    "fmt"
    "math"
)
func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    }
    return lim
}
func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
}

 
在 if 的簡單語句處定義的變數同樣可以在任何對應的 else 塊中使用。
複製代碼 代碼如下:
package main
import (
    "fmt"
    "math"
)
func pow(x, n, lim float64) float64 {
    if v := math.Pow(x, n); v < lim {
        return v
    } else {
        fmt.Printf("%g >= %g\n", v, lim)
    }
        // 不能在這裡使用 v,因此
    return lim
}
func main() {
    fmt.Println(
        pow(3, 2, 10),
        pow(3, 3, 20),
    )
}

希望本文所述對大家的Go語言程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.