将类型变量传递给函数进行类型断言
您希望通过将类型传递给函数来执行类型断言。本质上,您的目标是实现以下目标:
// 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