无法在结构体中嵌套结构体。

huangapple go评论113阅读模式
英文:

Cannot embed struct in struct

问题

我有以下两个结构体:

  1. type Profile struct {
  2. Email string `json:"email"`
  3. Username string `json:"username"`
  4. Name string `json:"name"`
  5. Permissions []string `json:"permissions"`
  6. }
  7. type Session struct {
  8. Token string `json:"token"`
  9. User Profile `json:"user"`
  10. }

我正在尝试使用以下代码创建一个新的Session

  1. session := Session{token, profile}

其中token是一个字符串,profile是之前创建的Profile

当我编译时,我得到了错误信息*cannot use profile (type Profile) as type Profile in field value

我是否漏掉了什么?

英文:

I have the following two structs:

  1. type Profile struct {
  2. Email string `json:"email"`
  3. Username string `json:"username"`
  4. Name string `json:"name"`
  5. Permissions []string `json:"permissions"`
  6. }
  7. type Session struct {
  8. Token string `json:"token"`
  9. User Profile `json:"user"`
  10. }

and I'm trying to create a new Session using:

  1. 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结构体如下:

  1. type Session struct {
  2. Token string `json:"token"`
  3. User *Profile `json:"user"`
  4. }

要么对其进行解引用。

  1. session := Session{Token: token, User: *profile}
英文:

Your profile is a pointer. Either redefine your Session to be

  1. type Session struct {
  2. Token string `json:"token"`
  3. User *Profile `json:"user"`
  4. }

or dereference it.

  1. session := Session{token, *profile}

huangapple
  • 本文由 发表于 2015年5月26日 22:27:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/30461409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定