猿问

将切片中的值分组为新类型

我在根据位置将 user1 和 user2 分组到新类型时遇到问题


type Chat struct {

location string

userName string

}


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

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

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


type result struct {

location string

chat []Chat

}


守候你守候我
浏览 83回答 1
1回答

慕田峪7331174

假设您只想按位置字符串分组并从中创建结果结构,则可以使用地图: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}]}
随时随地看视频慕课网APP

相关分类

Go
我要回答