我试图通过将类型传递给函数来实现类型断言。换句话说,我正在尝试实现这样的目标:
// 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)
}
方法是使用您想要匹配的类型的样本。
关于go - 将类型变量传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40895901/