Go 将类型变量传入函数
我试图通过将类型传递到函数中来实现类型断言。换句话说,我正在努力实现这样的目标:Go 将类型变量传入函数,go,type-conversion,type-assertion,Go,Type Conversion,Type Assertion,我试图通过将类型传递到函数中来实现类型断言。换句话说,我正在努力实现这样的目标: // 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
// 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
中的类型断言?@hlin117
嘿,如果我正确理解了你的问题,你需要比较这些类型,你可以做以下几点:
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)
}
方法是使用您希望匹配的类型的示例