英文:
Referencing yourself inside of a struct
问题
假设我有一个结构体类型如下:
type Authorization struct {
Username string
Password string
Handler func(http.HandlerFunc) http.HandlerFunc
}
并且我有一个这样的数组:
type Authorizations map[string]*Authorization
我想要能够像这样做:
var auth = Authorizations{
"test": &Authorization{
Username: "someusername",
Password: "somepassword",
Handler: self.BasicAuth,
},
}
假设 self.BasicAuth(显然不起作用)是 Authorization 类型上的一个方法。那么在语法上,正确的做法是什么?
英文:
Let's say I have a type that's a struct like so:
type Authorization struct {
Username string
Password string
Handler func(http.HandlerFunc) http.HandlerFunc
}
And I have an array of these:
type Authorizations map[string]*Authorization
I want to be able to do something like this:
var auth = Authorizations{
"test": *Authorization{
"someusername",
"somepassword",
self.BasicAuth,
},
}
Assume that self.BasicAuth (which obviously doesn't work) is a method on the Authorization type. What is the syntactically correct way to do this?
答案1
得分: 4
你不能在声明中引用一个值本身。你需要先初始化该值,然后才能将你想要使用的方法赋给Handler。
testAuth := &Authorization{
Username: "someusername",
Password: "somepassword",
}
testAuth.Handler = testAuth.HandleFunc
auths := Authorizations{
"test": testAuth,
}
英文:
You can't refer to a value inside its own declaration. You need to initialize the value first, then you can assign the method you want to use to Handler.
testAuth := &Authorization{
Username: "someusername",
Password: "somepassword",
}
testAuth.Handler = testAuth.HandleFunc
auths := Authorizations{
"test": testAuth,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论