2016-11-30 83 views
0

我试图通过将类型传入函数来实现类型断言。换句话说,我想实现这样的事情:Golang:将类型变量传入函数

// 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执行类型说法对吗?

+1

类型断言需要特定的类型。描述你正试图解决的更高层次的问题。什么是“做其他事情”? –

回答

2

写这样的:

func myfunction(jsonString string, v interface{}) { 
    err := json.Unmarshal([]byte(jsonString), v) 
    ... do other stuff 
} 

func main() { 
    var v map[string]string 
    myfunction("{'hello': 'world'}", &v) 
} 

在这个例子中,JSON文本将被解组到地图[字符串]字符串。不需要类型断言。

+1

谢谢。我让帖子更通用,所以它不包含有关json编组的任何内容。我仍然好奇如何通过Go中的类型断言,所以我编辑了这篇文章。 – hlin117

1

@ 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) 

} 

的方法是使用类型的样本你想匹配。

相关问题