[英]How to read an slice of like []interface{} in Go?
我有這樣的事情:
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
現在,我想讀取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
的值,如果斷言成功,則該值為true。 這是適合您的情況的簡單代碼示例:
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
}
}
}
你是這個意思嗎
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)
}
}
此代碼示例可能會幫助:
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
你:
{string s} //字符串接口
[{string t}] //字符串接口的切片
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.