英文:
Cannot embed struct in struct
问题
我有以下两个结构体:
type Profile struct {
Email string `json:"email"`
Username string `json:"username"`
Name string `json:"name"`
Permissions []string `json:"permissions"`
}
type Session struct {
Token string `json:"token"`
User Profile `json:"user"`
}
我正在尝试使用以下代码创建一个新的Session:
session := Session{token, profile}
其中token是一个字符串,profile是之前创建的Profile。
当我编译时,我得到了错误信息*cannot use profile (type Profile) as type Profile in field value。
我是否漏掉了什么?
英文:
I have the following two structs:
type Profile struct {
Email string `json:"email"`
Username string `json:"username"`
Name string `json:"name"`
Permissions []string `json:"permissions"`
}
type Session struct {
Token string `json:"token"`
User Profile `json:"user"`
}
and I'm trying to create a new Session using:
session := Session{token, profile}
where token is a string and profile is a Profile both created earlier.
I'm getting the error *cannot use profile (type Profile) as type Profile in field value when I compile.
Am I missing something?
答案1
得分: 4
你的profile是一个指针。要么重新定义你的Session结构体如下:
type Session struct {
Token string `json:"token"`
User *Profile `json:"user"`
}
要么对其进行解引用。
session := Session{Token: token, User: *profile}
英文:
Your profile is a pointer. Either redefine your Session to be
type Session struct {
Token string `json:"token"`
User *Profile `json:"user"`
}
or dereference it.
session := Session{token, *profile}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论