
在不知道確切類型的情況下迭代Go 中的資料結構
問題:
我們如何迭代資料結構(數組或映射)在Go中沒有確切的知識type?
嘗試失敗:
下面的程式碼嘗試迭代表示映射或數組的介面並對每個專案執行函數,但失敗由於型別檢查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | func DoTheThingToAllTheThings(data_interface interface {}) int {
var numThings int
switch data := data_interface.(type) {
case map[ interface {}] interface {}:
numThings = len(data)
case [] interface {}:
numThings = len(data)
default :
fmt.Println( "uh oh!" )
}
return numThings
}
|
登入後複製
解:
fmt.Printf("%vn", data_interface) 函數提供了一種無需類型即可迭代資料結構的方法-
1 2 3 | func PrintData(data_interface interface {}) {
fmt.Printf( "%v\n" , data_interface)
}
|
登入後複製
這有效是因為fmt.Printf 中的%v 動詞使用反射來確定參數的類型並相應地列印它。
Go中的反射:
fmt.Printf函數內部使用reflect套件檢查參數的類型參數並決定如何格式化它。 Reflect.ValueOf(arg)傳回一個reflect.Value對象,它代表參數的實際值,reflect.TypeOf(arg)傳回值的類型。
範例:
以下程式碼反映了一個 Board結構,然後將其重新構造為相同的新變數type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | type Board struct {
Tboard [9]string
Player1 Player
Player2 Player
}
func main() {
myBoard := makeBoard()
v := reflect.ValueOf(*myBoard)
t := v.Type()
var b2 Board
b2 = v.Interface().(Board)
fmt.Printf( "v converted back to: %#v\n" , b2)
}
|
登入後複製
注意:
為了使用反射,必須導出資料結構的類型,這意味著它必須以大寫字母開頭。
以上是如何在 Go 中迭代未知的資料結構?的詳細內容。更多資訊請關注PHP中文網其他相關文章!