在golang中嵌入结构会出错“未知字段”

时间:2017-01-16 23:28:41

标签: inheritance go struct compiler-errors compilation

我的用户包中有struct名为account

type Account struct {
    Tp          string `json:"type"bson:"type"`
    AccountId   string  `json:"account_id"bson:"account_id"`
    Credentials map[string]interface{} `json:"credentials,omitempty"bson:"credentials,omitempty"`
    ProfilePicture string `json:"profile_picture,omitempty"`
    Username string `json:"username"bson:"username"`
    AccessToken map[string]interface{}`bson:"access_token,omitempty"`
}

并在user/accounts中尝试将此帐户结构嵌入到另一个结构

type returnAccount struct {
    user.Account
    AccessToken string `json:"access_token,omitempty"`
}

用户包在尝试嵌入之前已正确导入我正在成功使用

最后一个循环我正在获取用户帐户并制作returnAccount的地图并从我的函数返回 这是我的功能

func getAccounts(usr *user.AuthenticatedUser, id ...string) (accounts map[string]returnAccount) {
    accounts = make(map[string]returnAccount)
    if len(id) > 0 {
        for _, v := range id {
            for _, acnt := range usr.Accounts {
                if acnt.AccountId == v {
                    accounts[acnt.AccountId] = returnAccount{
                        Tp:       acnt.Tp,
                        AccountId:acnt.AccountId,
                    }
                }
            }
        }
        return
    }
    for _, v := range usr.Accounts {
        accounts[v.AccountId] = returnAccount{
            Tp:       v.Tp,
            AccountId:v.AccountId,
            Username: v.Username,

        }

    }
    return
}

但是这段代码不会在这里编译是错误消息

# sgin/api/user/accounts
api/user/accounts/getaccounts.go:16: unknown returnAccount field 'Tp' in struct literal
api/user/accounts/getaccounts.go:17: unknown returnAccount field 'AccountId' in struct literal
api/user/accounts/getaccounts.go:26: unknown returnAccount field 'Tp' in struct literal
api/user/accounts/getaccounts.go:27: unknown returnAccount field 'AccountId' in struct literal
api/user/accounts/getaccounts.go:28: unknown returnAccount field 'Username' in struct literal
一切似乎都非常简单和简单我无法弄清楚为什么我得到这个错误我需要达到的帐户结构的所有成员都被导出

我需要这个字段的原因是我想通过api向客户端发送访问令牌,但不是秘密,我也希望减少缩进级别

3 个答案:

答案 0 :(得分:7)

您无法直接初始化嵌入类型中的字段,但您可以这样做:

accounts[v.AccountId] = returnAccount{
    Account: Account{
        Tp:        v.Tp,
        AccountId: v.AccountId,
        Username:  v.Username,
    },
}

或者,如果v的类型为Account,则可以使用

accounts[v.AccountId] = returnAccount{
    Account: v,
}

答案 1 :(得分:3)

您正在尝试初始化推文字段,这是复合文字无法实现的。来自Go spec

  

如果 x.f 是表示该字段或方法f的合法选择器,则会调用struct x中匿名字段的字段或方法f。

     

提升字段的作用类似于结构的普通字段,除了它们不能用作复合文字中的字段名称   结构

但您可以使用点符号访问它们:

ra:= returnAccount{}
ra.Tp = acnt.Tp

答案 2 :(得分:-1)

returnAccount应该以大写字母开头,以便在其他程序包中导出和使用。

在Go中,一个简单的规则确定要导出的标识符,而不是:导出的标识符以大写字母开头。

相关问题