我为[] 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})
答案 0 :(得分:1)
test([]interface{1, 2, 3})
错误,应为test(state{1,2,3})
。
您也可以使用s[x]
:
type state []interface{}
func test(s state) {
fmt.Println(s[0])
}
func main() {
test(state{1, 2, 3})
}
答案 1 :(得分:0)
package main
import (
"fmt"
"log"
)
type state []interface{}
func (s state) item(index int) (interface{}, error) {
if len(s) <= index {
return nil, fmt.Errorf("Index out of range")
}
return s[index], nil
}
func main() {
st := state{1, 2, 3}
// get sub item
it, err := st.item(0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("First Item %v\n", it)
// cast back to []interface{}
items := []interface{}(st)
fmt.Println(items)
}