亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang:如何從 []interface{} 別名獲取子元素

golang:如何從 []interface{} 別名獲取子元素

Go
精慕HU 2021-08-16 18:35:56
我為 []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})
查看完整描述

2 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

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

}


查看完整回答
反對 回復 2021-08-16
?
千巷貓影

TA貢獻1829條經驗 獲得超7個贊

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)

}


查看完整回答
反對 回復 2021-08-16
  • 2 回答
  • 0 關注
  • 367 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號