」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何存取 Go if 語句內部宣告的變數?

如何存取 Go if 語句內部宣告的變數?

發佈於2025-01-18
瀏覽:949

How Can I Access Variables Declared Inside a Go `if` Statement Outside of It?

條件語句中的變數作用域

在 Go 中,在 if 語句作用域內宣告的變數僅在該區塊內可見。當需要使用條件語句外部聲明的變數時,這可能會帶來挑戰。

考慮以下程式碼:

if len(array1) > len(array2) {
    new1 := make([]string, 0, len(array1))
}

// Error: new1 is not visible here
new2 := make([]string, 0, len(new1))

在此範例中,變數 new1 在 if 語句中聲明,並且只能在該範圍內使用。要解決此問題,new1 必須在 if 語句外部聲明並在其中初始化。

var new1 []string

if len(array1) > len(array2) {
    new1 = make([]string, 0, len(array1))
} else {
    new1 = make([]string, 0, len(array2))
}

new2 := make([]string, 0, len(new1))

現在,new1 在 if 語句之外聲明,並且可以在 if 和 else 區塊中存取。這允許它在後續程式碼中使用,並作為參數傳遞給 make.

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3