为什么字段部分没有嵌入

时间:2015-04-16 18:25:33

标签: go

我有以下结构

package router

import (
    "io"
    "net/http"
    "townspeech/components/i18n"
    "townspeech/components/policy"
    "townspeech/components/session"
    "townspeech/controllers/base"
    "townspeech/types"
)

type sidHandler struct {
    req     *http.Request
    res     http.ResponseWriter
    handler sidFuncHandler
    section string
    err     *types.ErrorJSON
    sess    *session.Sid
}

我想嵌入另一个结构,如:

package router

import (
    "net/http"
    "townspeech/types"
    "townspeech/components/session"
    "townspeech/controllers/base"
)

type authHandler struct {
    sidHandler
    handler authFuncHandler
    auth    *session.Auth
}

使用authHandler结构的函数:

func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
    return &authHandler{handler: handler, section: section}
}

编译器抱怨:

# app/router
../../../router/funcs.go:9: unknown authHandler field 'section' in struct literal
FAIL    app/test/account/validation [build failed]

如您所见,两个结构都在同一个包中,字段不应该显示为私有。
我做错了什么?

2 个答案:

答案 0 :(得分:2)

您无法在结构文字中引用提升字段。您必须创建嵌入类型,并按类型名称引用它。

&authHandler{
    sidHandler: sidHandler{section: "bar"},
    handler:    "foo",
}

答案 1 :(得分:2)

嵌入不适用于那样的文字。

func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
    return &authHandler{
        handler: handler,
        sidHandler: sidHandler{section: section},
    }
}