猿问

golang:如何从 []interface{} 别名获取子元素

我为 []interface{} 定义了一个别名:


type state []interface{}

如何在 State 中获取子项:


func test(s state) {

    // How to get 1st element in s ?

    // or How to convert s back to []interface{} ?

}


test([]interface{1, 2, 3})


精慕HU
浏览 347回答 2
2回答

慕仙森

test([]interface{1, 2, 3})错了,应该是test(state{1,2,3})。您还可以像访问任何切片一样访问 s 中的第一个元素,使用s[x]:type state []interface{}func test(s state) {    fmt.Println(s[0])}func main() {    test(state{1, 2, 3})}

千巷猫影

package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log")type state []interface{}func (s state) item(index int) (interface{}, error) {&nbsp; &nbsp; if len(s) <= index {&nbsp; &nbsp; &nbsp; &nbsp; return nil, fmt.Errorf("Index out of range")&nbsp; &nbsp; }&nbsp; &nbsp; return s[index], nil}func main() {&nbsp; &nbsp; st := state{1, 2, 3}&nbsp; &nbsp; // get sub item&nbsp; &nbsp; it, err := st.item(0)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("First Item %v\n", it)&nbsp; &nbsp; // cast back to []interface{}&nbsp; &nbsp; items := []interface{}(st)&nbsp; &nbsp; fmt.Println(items)}
随时随地看视频慕课网APP

相关分类

Go
我要回答