首頁  >  文章  >  後端開發  >  如何從 Go 中的 for 迴圈傳回介面清單?

如何從 Go 中的 for 迴圈傳回介面清單?

王林
王林轉載
2024-02-09 12:10:18330瀏覽

如何从 Go 中的 for 循环返回接口列表?

在Go語言中,我們可以透過for迴圈來遍歷陣列、切片、映射等資料結構。但是,有時候我們需要在循環中回傳一個介面清單。這是一個常見的需求,因為介面是一種抽象類型,可以代表多種具體類型。本文將介紹如何在Go中使用for迴圈返回介面清單。首先,我們需要理解Go中的介面類型和類型斷言的概念。

問題內容

如何從 go 中的 for 迴圈傳回介面清單? 假設我有以下數據:

id name project_type
1 project_name 1
2 project_name 1
3 project_name 1
4 project_name 2
5 project_name 2
6 project_name 3
7 project_name 3
8 project_name 3
9 project_name 4
10 project_name 4

我可以使用下面的go程式碼來取得project_type=1和project_type=2的兩個列表,

func (d *db) projectlist(type, uid string, size uint64) (interface{}, interface{}, error) {
    type resp struct {
        name            string  `json:"name"`
        id             string  `json:"id"`
        projecttype    string  `json:"project_type"`

    }

    var project_type_1 []*resp
    var project_type_2 []*resp

    sql = fmt.sprintf(sql, where.string())
    _, err := d.ctx.db().selectbysql("select * from project where project_type=1 order by rand() limit 10").load(&project_type_1)

    _, err = d.ctx.db().selectbysql("select * from project where project_type=2 order by rand() limit 10").load(&project_type_2)
    return project_type_1, project_type_2, err
}

但是現在project_type的資料是的json[{"project_type":1,"name":"something else"},{"project_type":2,"name":"something else"},{ "project_type":3,"name":"something else"},{"project_type":4,"name":"something else"}],project_type大於2,我必須取得一個interface{}列表,我嘗試重寫如下程式碼,但我不知道下一步該怎麼寫,如何從go中的for循環返回介面列表?非常感謝您的建議。

func newprojectlist(d *db) ([]interface{}, error) {
    var s = make([]projecttype, 0)
    data, err := d.querystring("project_type")
    if err != nil {
        return nil, err
    }

    err = json.unmarshal([]byte(data), &s)
    if err != nil {
        return nil, err
    }

    for _, shorttype := range s {
        fmt.println("this is shorttype", shorttype)
    }
    return nil, err

}

解決方法

如果您希望每個project_type有10個結果(全部10*n個結果):

func (d *db) projectlist(type, uid string, size uint64) ([]interface{}, error) {
    type resp struct {
        name        string `json:"name"`
        id          string `json:"id"`
        projecttype string `json:"project_type"`
    }
    // get all types, you can get it from db
    // example: select distinct projecttype from project
    types := []string{"1", "2", "3", "4"}
    ans := []interface{}{}

    for _, stype := range types {
        var project_type []*resp
        sql = fmt.sprintf(sql, where.string())
        _, err := d.ctx.db().selectbysql("select * from project where project_type=" + stype + " order by rand() limit 10").load(&project_type)
        ans = append(ans, project_type)
    }
    return ans, nil
}

如果所有型別總共有 10 個結果:

i write it if you need it

以上是如何從 Go 中的 for 迴圈傳回介面清單?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除