将类型变量传递给函数 [英] Passing in a type variable into function
本文介绍了将类型变量传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过将类型传入函数来实现类型断言.换句话说,我正在尝试实现以下目标:
I'm trying to achieve a type assertion by passing in a type into a function. In other words, I'm trying to achieve something like this:
// Note that this is pseudocode, because Type isn't the valid thing to use here
func myfunction(mystring string, mytype Type) {
...
someInterface := translate(mystring)
object, ok := someInterface.(mytype)
... // Do other stuff
}
func main() {
// What I want the function to be like
myfunction("hello world", map[string]string)
}
要在myfunction
中成功执行类型断言,我需要在myfunction
中使用什么正确的函数声明?
What's the proper function declaration I need to use in myfunction
, to successfully perform the type assertion in myfunction
?
推荐答案
@ hlin117,
@hlin117,
嘿,如果我正确理解了您的问题,并且需要比较类型,请按照以下步骤操作:
Hey, if I understood your question correctly and you need to compare the types, here's what you can do:
package main
import (
"fmt"
"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)
assertMatch := myfunction("hello world", "stringSample")
fmt.Printf("%+v\n", assertMatch)
}
方法是使用您要匹配的类型的样本.
The approach is to use a sample of the type you'd like to match.
这篇关于将类型变量传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文