2017-02-01 13 views
0

あなたはその質問について助言していただけますか? 私はゴーランを学び始めたばかりで、すでにこの状況で窒息しています。例えばgolang、関数に引数としてstructsを使用してください

package main 

import (
    "fmt" 
) 
type X struct{ 
    x string 
} 
type Y struct{ 
    y string 
} 

func main() { 
    var x []X 
    var y []Y 

    f(x) 
    f(y) 
} 

func f(value interface{}){ 
    if(typeof(value) == "[]X"){ 
     fmt.Println("this is X") 
    } 
    if(typeof(value) == "[]Y"){ 
     fmt.Println("this is Y") 
    } 
} 

expected output: this is X 
       this is Y 

value interface{}は間違ったタイプです。どのようにして一つの関数に異なる構造体を入れ、その型を動的に定義できますか?

これは可能でしょうか?おかげさまで

+1

あなたは同じ名前の変数と関数を持っています。あなたは何をしようとしていますか? – JimB

+0

が更新されました。希望は、今それは明確です – touchman

+0

タイプアサーションまたはタイプスイッチをお探しですか?可能な重複:https://stackoverflow.com/questions/6996704/how-to-check-variable-type-at-runtime-in-go-language – JimB

答えて

4

可能な正確なタイプがわかっている場合は、type switchを使用することができます。それ以外の場合はreflectパッケージを使用することができます。ここで

は型スイッチアプローチを実証コードです:

package main 

import (
    "fmt" 
) 

type X struct { 
    x string 
} 
type Y struct { 
    y string 
} 

func main() { 
    var x = []X{{"xx"}} 
    var y = []Y{{"yy"}} 

    f(x) 
    f(y) 
} 

func f(value interface{}) { 
    switch value := value.(type) { 
    case []X: 
     fmt.Println("This is X", value) 
    case []Y: 
     fmt.Println("This is Y", value) 
    default: 
     fmt.Println("This is YoYo") 
    } 
} 

プレーリンク:here

+0

ありがとうございます – touchman

関連する問題