首頁 > 後端開發 > Golang > 主體

為什麼 Go 包含「goto」語句?

Barbara Streisand
發布: 2024-11-13 16:31:02
原創
813 人瀏覽過

Why Does Go Include the 'goto' Statement?

Go's Measured Use of the 'goto' Statement

Curiosity often arises around the presence of the 'goto' statement in Go, given its historical association with code obfuscation and flow complications. One might question why Google chose to include it.

Upon reviewing the Go standard library, we find instances where the 'goto' statement is employed judiciously.

For example, in the math/gamma.go file, 'goto' helps simplify control flow. Without it, the code would require additional variables and conditional checks, making it less readable and intuitive:

for x < 0 {
    if x > -1e-09 {
        goto small
    }
    z = z / x
    x = x + 1
}
...
small:
    if x == 0 {
        return Inf(1)
    }
    return z / ((1 + Euler*x) * x)
}
登入後複製

Here, 'goto' eliminates the need for a temporary boolean variable to track the flow, resulting in a more concise and clear code structure.

It's important to note that Go's use of 'goto' is constrained by specific rules. 'goto' must not jump over variable declarations or into different code blocks. These restrictions prevent the statement's potential for abuse while retaining its usefulness in specific scenarios like the above.

以上是為什麼 Go 包含「goto」語句?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板