亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不懂 Go 中的組合

不懂 Go 中的組合

Go
繁花不似錦 2021-10-04 18:09:24
在下面的示例中,我已嵌入http.ResponseWriter到我自己的名為Response. 我還添加了一個名為Status. 為什么我不能從我的root處理程序函數內部訪問該字段?當我打印出w根處理程序函數中的類型時main.Response,它說它的類型看起來是正確的,當我打印出結構的值時,我可以看到它Status在那里。為什么我不能通過 go 訪問w.Status?這是標準輸出的內容:main.Response{ResponseWriter:0xc2080440a0 Status:0}代碼:package mainimport (    "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)}
查看完整描述

1 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

w是一個類型的變量http.ResponseWriter。ResponseWriter沒有字段或方法Status,只有您的Response類型。


http.ResponseWriter是一種接口類型,并且由于您的Response類型實現了它(因為它嵌入了ResponseWriter),該w變量可能包含動態類型的值Response(在您的情況下它確實如此)。


但是要訪問該Response.Status字段,您必須將其轉換為 type 的值Response。為此使用類型斷言:


if resp, ok := w.(Response); ok {

    // resp is of type Response, you can access its Status field

    fmt.Println(resp.Status) // <--- properly prints status

}


查看完整回答
反對 回復 2021-10-04
  • 1 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號