gpt4 book ai didi

go - 如何将类型为其他结构的 map 添加到 map ?

转载 作者:行者123 更新时间:2023-12-01 22:43:46 24 4
gpt4 key购买 nike

type Email struct { 

From string
To string
Body string

}

type User struct {

Inbox map[string]Email
Outbox map[string]Email

}

如何为用户映射/初始化添加值?我非常困惑,如果不是类型Email,我可以添加到用户 map 中,但这非常令人困惑。

最佳答案

map值默认为nil,除非您通过make对其进行初始化。因此,为自己节省一些样板,请为任何具有映射的类型创建一个“构造函数”,以便为您执行此初始化操作,例如

func newUser() User {
return User{
Inbox: make(map[string]Email),
Outbox: make(map[string]Email),
}
}

使用方法:
u := newUser()
u.Inbox["gmail#56"] = Email{
From: "me",
To: "you",
Body: "how are you?",
}
u.Outbox["outlook#25"] = Email{
From: "Mr. Smith",
To: "Bossman",
Body: "report is done?",
}

游乐场示例: https://play.golang.org/p/3LLurNsDJER

您还可以内联初始化 map ,但是语法非常繁琐:
u := User{
Inbox: map[string]Email{"gmail": Email{From: "me", To: "you", Body: "how are you?"}},
Outbox: map[string]Email{"outlook": Email{From: "Mr. Smith", To: "Bossman", Body: "report is done?"}},
}

关于go - 如何将类型为其他结构的 map 添加到 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60659483/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com