hli*_*117 9 type-conversion go 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.(mytype)
... // Do other stuff
}
func main() {
// What I want the function to be like
myfunction("hello world", map[string]string)
}
Run Code Online (Sandbox Code Playgroud)
我需要使用哪种正确的函数声明myfunction,才能成功执行类型断言myfunction?
小智 5
@ 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)
}
Run Code Online (Sandbox Code Playgroud)
方法是使用您想要匹配的类型的样本.