2015-04-16 43 views
1

,我有以下結構爲什麼外地部分沒有得到嵌入

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

嵌入不適用於這樣的文字。

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

您不能在結構體文字中引用提升字段。您必須創建嵌入類型,並通過類型的名稱引用它。

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

例如:https://play.golang.org/p/uwvxaaCo4V –

相關問題