」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Go 中將類型變數傳遞給函數進行類型斷言?

如何在 Go 中將類型變數傳遞給函數進行類型斷言?

發佈於2024-11-08
瀏覽:630

How to Pass Type Variables to Functions for Type Assertions in Go?

將類型變數傳遞給函數進行型別斷言

您希望透過將型別傳遞給函式來執行型別斷言。本質上,您的目標是實現以下目標:

// Note that this is pseudocode, because Type isn't valid here
func myfunction(mystring string, mytype Type) {
    ...

    someInterface := translate(mystring)
    object, ok := someInterface.(mytype)

    ...  // Do other stuff
}

func main() {
    // Desired function call
    myfunction("hello world", map[string]string)
}

要在 myfunction 中成功執行型別斷言,請使用下列函數宣告:

package main

import "reflect"

func myfunction(v interface{}, mytype interface{}) bool {
    return reflect.TypeOf(v) == reflect.TypeOf(mytype)
}

func main() {
    assertNoMatch := myfunction("hello world", map[string]string{})
    fmt.Printf("% v\n", assertNoMatch) // false

    assertMatch := myfunction("hello world", "stringSample")
    fmt.Printf("% v\n", assertMatch) // true
}

此方法涉及使用要匹配的類型的範例,確保類型相同以實現成功的類型斷言。

最新教學 更多>

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

Copyright© 2022 湘ICP备2022001581号-3