2017-02-01 32 views
0

你能否就這個問題提出建議。 我剛開始學習golang,並已經因這種情況而窒息。golang,使用結構作爲函數的參數

例如:

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