2016-11-30 15 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テキストは、[文字列]文字列のマップに非整列化されます。型アサーションは必要ありません。 hlin117 @

+1

ありがとうございます。私はポストをより一般的なものにしたので、jsonマーシャリングに関するものは何も含まれていません。私はまだGoのタイプアサーションでどのように渡すのか不思議であるので、これを反映するように投稿を編集しました。 – hlin117

1

ねえ、私が正しくあなたの質問を理解し、あなたはタイプを比較する必要がある場合は、ここで何ができるかです:

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) 

} 

アプローチはタイプのサンプルを使用することですあなたは一致したいと思います。

関連する問題