”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 Go 中将类型变量传递给函数进行类型断言?

如何在 Go 中将类型变量传递给函数进行类型断言?

发布于2024-11-08
浏览:156

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