我有這樣的事情:如何在Go中讀取類似[] interface {}的片段?
a := []interface{}{}
b := []interface{}{}
type S struct {
text string
}
s := S{"string"}
t := S{"string"}
a = append(a, s)
b = append(b, t)
a := append(a, b)
a
現在我想讀的元素,或元素的元素..但如何?
我有這樣的事情:如何在Go中讀取類似[] interface {}的片段?
a := []interface{}{}
b := []interface{}{}
type S struct {
text string
}
s := S{"string"}
t := S{"string"}
a = append(a, s)
b = append(b, t)
a := append(a, b)
a
現在我想讀的元素,或元素的元素..但如何?
你想被稱爲類型的斷言什麼。 http://golang.org/ref/spec#Type_assertions
該網頁上的簡單的例子是:
var x interface{} = 7 // x has dynamic type int and value 7
i := x.(int) // i has type int and value 7`
另外要注意的是,一種類型的斷言返回一個名爲ok
值,如果斷言是成功,是真實的。下面是你的情況下,簡單的代碼示例:
a := []interface{}{}
b := []interface{}{}
type S struct {
text string
}
s := S{"string"}
t := S{"string"}
a = append(a, s)
b = append(b, t)
a = append(a, b)
assertedS,ok := a[0].(S)
if !ok { // If this is, in fact, not a value of type S, something is wrong
// error handling
}
fmt.Println(assertedS) // Should show you the same thing as printing s
assertedB,ok := a[1].([]interface{})
if !ok {
//...
}
assertedT,ok := assertedB[0].(S)
if !ok {
//...
}
fmt.Println(assertedT) // Should show you the same thing as printing t
如果你不知道提前其中列表元素是什麼,你可以通過它進行迭代,並使用「型開關」。 http://golang.org/ref/spec#Switch_statements
switch x.(type) {
// cases
}
,它允許您基於什麼類型的存儲的接口{}真的是執行條件的行爲。
例如,你可以使用
func ExtractSlice(a []interface{}) {
for _,x := range a {
switch i := x.(type) {
case S:
fmt.Println(i)
case []interface{}:
ExtractSlice(i) // Recursively unpacks b once it's found within a
}
}
}
This code example可以幫助:
package main
import "fmt"
func main() {
a := []interface{}{}
b := []interface{}{}
type S struct {
text string
}
s := S{"string s"}
t := S{"string t"}
a = append(a, s)
b = append(b, t)
a = append(a, b)
for _, v := range a {
fmt.Println(v)
}
}
但要注意,你已經定義a
和b
作爲接口切片。這意味着,當你做a = append(a, b)
你把b
切片現有a
串後的a
片,因此,當你在range
你a
得到:
{字符串s} //字符串的接口
[{串T} //字符串接口的片
你的意思呢?
a := []interface{}{}
b := []interface{}{}
type S struct {
text string
}
s := S{"string"}
t := S{"string"}
a = append(a, s)
b = append(b, t)
a = append(a, b)
for _, v := range a {
switch v.(type) {
case S:
fmt.Println("S", v)
default:
fmt.Println("Slice", v)
}
}
這是關於切片的元素。那麼**元素的**元素如何呢?我猜我們需要'反映'來做到這一點,但我不知道如何? – jiyinyiyong