Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must the http.Request argument be a pointer?

Tags:

pointers

go

package main

import (
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request){
        w.Write([]byte("hello world"))
    })
    http.ListenAndServe(":8000", nil)
}

If I remove the * in http.Request:

github.com/creating_web_app_go/main.go:8: cannot use func literal (type func(http.ResponseWriter, http.Request)) as type func(http.ResponseWriter, *http.Request) in argument to http.HandleFunc

I'm very new to both Go and pointers.

So the Question is, why must http.Request be a pointer rather than a func literal? Can anyone explain this in the simplest way possible, with perhaps a reference to source code?

like image 290
Armeen Harwood Avatar asked Dec 01 '22 17:12

Armeen Harwood


1 Answers

Because it's a large struct. Copying it would be expensive. So it's a pointer to a struct, which is common in Go when structs are large. Also it has some state, so it would likely be confusing if it were copied. It would make no sense to be a func literal; I don't understand why that would be an option.

like image 180
Rob Napier Avatar answered Dec 04 '22 13:12

Rob Napier