Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Struct Don';我不懂围棋的作文_Struct_Interface_Go_Composition - Fatal编程技术网

Struct Don';我不懂围棋的作文

Struct Don';我不懂围棋的作文,struct,interface,go,composition,Struct,Interface,Go,Composition,在下面的示例中,我将http.ResponseWriter嵌入到自己的名为Response的结构中。我还添加了一个名为Status的额外字段。为什么我不能从根处理函数中访问该字段 当我在我的根处理函数中打印出w类型时,它表示它是main.Response类型,这似乎是正确的,当我打印出结构的值时,我可以看到Status存在。为什么我不能通过访问w.Status 这是stdout的内容: main.Response {ResponseWriter:0xc2080440a0 Status:0} 代

在下面的示例中,我将
http.ResponseWriter
嵌入到自己的名为
Response
的结构中。我还添加了一个名为
Status
的额外字段。为什么我不能从
根处理函数中访问该字段

当我在我的根处理函数中打印出
w
类型时,它表示它是
main.Response
类型,这似乎是正确的,当我打印出结构的值时,我可以看到
Status
存在。为什么我不能通过访问
w.Status

这是stdout的内容:

main.Response
{ResponseWriter:0xc2080440a0 Status:0}
代码:

主程序包
进口(
“fmt”
“反映”
“net/http”
)
类型响应结构{
http.ResponseWriter
状态int
}
func(r响应)写入头(n int){
r、 状态=n
r、 负责人(n)
}
func中间件(hhttp.Handler)http.Handler{
返回http.HandlerFunc(func(w http.ResponseWriter,r*http.Request){
resp:=响应{ResponseWriter:w}
h、 ServeHTTP(resp,r)
})
}
func root(w http.ResponseWriter,r*http.Request){
w、 写入([]字节(“根”))
fmt.Println(反射类型(w))
格式打印F(“%+v\n”,w)

fmt.Println(w.Status)/
w
http类型的变量。ResponseWriter
ResponseWriter
没有字段或方法
Status
,只有您的
Response
类型

http.ResponseWriter
是一种接口类型,由于您的
Response
类型实现了它(因为它嵌入了
ResponseWriter
),因此
w
变量可能包含一个动态类型的值
Response
(在您的情况下,它确实如此)

但要访问
Response.Status
字段,必须将其转换为
Response
类型的值

如果响应,ok:=w(响应);ok{
//resp为响应类型,您可以访问其状态字段
fmt打印LN(各自状态)//
package main

import (
    "fmt"
    "reflect"

    "net/http"
)

type Response struct {
    http.ResponseWriter
    Status int
}

func (r Response) WriteHeader(n int) {
    r.Status = n
    r.ResponseWriter.WriteHeader(n)
}

func middleware(h http.Handler) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        resp := Response{ResponseWriter: w}

        h.ServeHTTP(resp, r)
    })
}

func root(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("root"))
    fmt.Println(reflect.TypeOf(w))
    fmt.Printf("%+v\n", w)
    fmt.Println(w.Status) // <--- This causes an error.
}

func main() {
    http.Handle("/", middleware(http.HandlerFunc(root)))
    http.ListenAndServe(":8000", nil)
}
if resp, ok := w.(Response); ok {
    // resp is of type Response, you can access its Status field
    fmt.Println(resp.Status) // <--- properly prints status
}