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

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

將切片中的值分組為新類型

將切片中的值分組為新類型

Go
守候你守候我 2022-08-24 10:30:15
我在根據位置將 user1 和 user2 分組到新類型時遇到問題type Chat struct {location stringuserName string}a := Chat{location:Cal, userName:"user1"}b := Chat{location:Cal, userName:"user2"}c := Chat{location:IL, userName:"user3"}type result struct {location stringchat []Chat}
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

假設您只想按位置字符串分組并從中創建結果結構,則可以使用地圖:


type Chat struct {

    location string

    userName string

}


type Result struct {

    location string

    chat     []Chat

}


func main() {

    a := Chat{location: "Cal", userName: "user1"}

    b := Chat{location: "Cal", userName: "user2"}

    c := Chat{location: "IL", userName: "user3"}


    x := []Chat{a, b, c}

    m := make(map[string]Result)

    for _, c := range x {

        if val, ok := m[c.location]; ok {

            chats := append(val.chat, c)

            m[c.location] = Result{location: c.location, chat: chats}

        } else {

            m[c.location] = Result{location: c.location, chat: []Chat{c}}


        }

    }


    for k, v := range m {

        fmt.Printf("%s -> %v\n", k, v)

    }

}

那會回來的


Cal -> {Cal [{Cal user1} {Cal user2}]}

IL -> {IL [{IL user3}]}



查看完整回答
反對 回復 2022-08-24
  • 1 回答
  • 0 關注
  • 74 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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