英文:
Why the field section does not get embedded
问题
我有以下的结构体:
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]
如你所见,这两个结构体位于同一个包中,字段section不应该是私有的。我做错了什么?
英文:
I have the following struct
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
}
And I want to embed in another struct like:
package router
import (
"net/http"
"townspeech/types"
"townspeech/components/session"
"townspeech/controllers/base"
)
type authHandler struct {
sidHandler
handler authFuncHandler
auth *session.Auth
}
And the function, that use the authHandler struct:
func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
return &authHandler{handler: handler, section: section}
}
The compiler complain:
# app/router
../../../router/funcs.go:9: unknown authHandler field 'section' in struct literal
FAIL app/test/account/validation [build failed]
As you can see, the two structs are in the same package, field section should not appear as private.
What am I doing wrong?
答案1
得分: 2
你不能在结构体字面值中引用提升的字段。你必须创建嵌入类型,并通过类型名称引用它。
&authHandler{
sidHandler: sidHandler{section: "bar"},
handler: "foo",
}
英文:
You can't refer to promoted fields in a struct literal. You have to create the embedded type, and refer to it by the type's name.
&authHandler{
sidHandler: sidHandler{section: "bar"},
handler: "foo",
}
答案2
得分: 2
嵌入式不适用于这样的文字。
func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
return &authHandler{
handler: handler,
sidHandler: sidHandler{section: section},
}
}
英文:
Embedding doesn't work with literals like that.
func registerAuthHandler(handler authFuncHandler, section string) http.Handler {
return &authHandler{
handler: handler,
sidHandler: sidHandler{section: section},
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论