在go中使用空接口
我正在努力理解公司使用的代码。我是新来的go lang,我已经在他们的官方网站上浏览了教程。然而,我很难将头脑集中在空接口上,即接口{}。从网上的各种来源,我发现空接口可以容纳任何类型。但是,我很难理解代码库,尤其是一些函数。我不会在这里发布全部内容,只会发布使用它的最小函数。请容忍我在go中使用空接口,go,Go,我正在努力理解公司使用的代码。我是新来的go lang,我已经在他们的官方网站上浏览了教程。然而,我很难将头脑集中在空接口上,即接口{}。从网上的各种来源,我发现空接口可以容纳任何类型。但是,我很难理解代码库,尤其是一些函数。我不会在这里发布全部内容,只会发布使用它的最小函数。请容忍我 Function (I am trying to understand): func (this *RequestHandler) CreateAppHandler(rw http.ResponseWrite
Function (I am trying to understand):
func (this *RequestHandler) CreateAppHandler(rw http.ResponseWriter, r *http.Request) *foo.ResponseError {
var data *views.Data = &views.Data{Attributes: &domain.Application{}}
var request *views.Request = &views.Request{Data: data}
if err := json.NewDecoder(r.Body).Decode(request); err != nil {
logrus.Error(err)
return foo.NewResponsePropogateError(foo.STATUS_400, err)
}
requestApp := request.Data.Attributes.(*domain.Application)
requestApp.CreatedBy = user
设置某些上下文时,RequestHandler
是与此代码在同一个包中定义的结构<代码>域和视图
是独立的包。应用程序是包域中的结构。以下两个结构是包视图的一部分:
type Data struct {
Id string `json:"id"`
Type string `json:"type"`
Attributes interface{} `json:"attributes"`
}
type Request struct {
Data *Data `json:"data"`
}
以下是json包的一部分:
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r}
}
func (dec *Decoder) Decode(v interface{}) error {
if dec.err != nil {
return dec.err
}
if err := dec.tokenPrepareForDecode(); err != nil {
return err
}
if !dec.tokenValueAllowed() {
return &SyntaxError{msg: "not at beginning of value"}
}
// Read whole value into buffer.
n, err := dec.readValue()
if err != nil {
return err
}
dec.d.init(dec.buf[dec.scanp : dec.scanp+n])
dec.scanp += n
// Don't save err from unmarshal into dec.err:
// the connection is still usable since we read a complete JSON
// object from it before the error happened.
err = dec.d.unmarshal(v)
// fixup token streaming state
dec.tokenValueEnd()
return err
}
type Decoder struct {
r io.Reader
buf []byte
d decodeState
scanp int // start of unread data in buf
scan scanner
err error
tokenState int
tokenStack []int
}
现在,我了解到,在包视图中的struct数据中,应用程序被设置为空接口的类型。然后,在同一个包中创建一个指向请求的指针,该指针指向变量数据
我有以下疑问:
数据
,仅分配空接口值,而不分配其他两个字段的值李>
json.NewDecoder(r.Body).解码(请求)
该
不是围棋中的关键词;这里可以使用任何变量名。这就是所谓的接收器。以这种方式声明的函数必须像thing.func(params)
一样调用,其中“thing”是接收器类型的表达式。在函数中,接收器设置为thing
的值接口{}
类型的值,可以使用类型断言或类型开关来确定值的类型,也可以使用反射来使用值,而不必为特定类型编写代码json
是声明函数NewDecoder
的包的名称。调用该函数,然后对该返回值调用Decode
函数(由NewDecoder
的返回值类型实现)