struct - Don't understand composition in Go -
in example below i've embedded http.responsewriter own struct called response. i've added field called status. why can't access field inside root handler function?
when print out type of w in root handler function says it's of type main.response seems correct , when print out values of struct can see status there. why can't access going w.status?
this contents of stdout:
main.response {responsewriter:0xc2080440a0 status:0} code:
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) // <--- causes error. } func main() { http.handle("/", middleware(http.handlerfunc(root))) http.listenandserve(":8000", nil) }
w variable of type http.responsewriter. responsewriter not have field or method status, response type.
http.responsewriter interface type, , since response type implements (because embeds responsewriter), w variable may hold value of dynamic type response (and in case does).
but access response.status field, have convert value of type response. use type assertion:
if resp, ok := w.(response); ok { // resp of type response, can access status field fmt.println(resp.status) // <--- prints status }
Comments
Post a Comment