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

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

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}

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:

确定