Referencing yourself inside of a struct

huangapple go评论78阅读模式
英文:

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,
}

huangapple
  • 本文由 发表于 2015年6月18日 06:42:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/30903721.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定