Golang:将类型变量传递给函数
发布时间:2020-12-16 19:04:33 所属栏目:大数据 来源:网络整理
导读:我试图通过将类型传入函数来实现类型断言.换句话说,我正在努力实现这样的目标: // Note that this is pseudocode,because Type isn't the valid thing to use herefunc myfunction(mystring string,mytype Type) { ... someInterface := translate(mystring
我试图通过将类型传入函数来实现类型断言.换句话说,我正在努力实现这样的目标:
// 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("%+vn",assertNoMatch) assertMatch := myfunction("hello world","stringSample") fmt.Printf("%+vn",assertMatch) } 方法是使用您想要匹配的类型的样本. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |