golang: how to get sub element from a []interface{} alias

huangapple go评论91阅读模式
英文:

golang: how to get sub element from a []interface{} alias

问题

我定义了一个别名为[]interface{}的类型state:

type state []interface{}

如何获取State中的子项:

func test(s state) {
    // 如何获取s中的第一个元素?
    // 或者如何将s转换回[]interface{}类型?
}

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

I defined a alias to []interface{}:

type state []interface{}

how to get subitems in 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})

答案1

得分: 1

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})
}

playground

英文:

test([]interface{1, 2, 3}) is wrong, it should be test(state{1,2,3}).

Also you access the first element in s like you would access any slice, with s[x]:

type state []interface{}

func test(s state) {
	fmt.Println(s[0])
}

func main() {
	test(state{1, 2, 3})
}

<kbd>playground</kbd>

答案2

得分: 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("索引超出范围")
    }

    return s[index], nil
}

func main() {
    st := state{1, 2, 3}

    // 获取子项
    it, err := st.item(0)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("第一个项 %v\n", it)

    // 转换回 []interface{}
    items := []interface{}(st)

    fmt.Println(items)
}

以上是要翻译的代码。

英文:
package main

import (
    &quot;fmt&quot;
    &quot;log&quot;
)

type state []interface{}

func (s state) item(index int) (interface{}, error) {
    if len(s) &lt;= index {
        return nil, fmt.Errorf(&quot;Index out of range&quot;)
    }

    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(&quot;First Item %v\n&quot;, it)

    // cast back to []interface{}
    items := []interface{}(st)

    fmt.Println(items)
}

huangapple
  • 本文由 发表于 2014年9月14日 23:41:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/25835009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定