since I did not find much related to this particular question I simply ask here:
Let’s assume we have an application with store, db connections, some services etc. Coming from php by now I injected such dependencies by pointer, e. g.:
service <- store <- db connection
But is this really the way to go in go? Or is it more proper to inject these dependencies by value?
Passing by value would create a copy. Consider this:
package main
import (
"fmt"
)
type Service struct {
counter int
}
func (service *Service) inc() {
service.counter = service.counter + 1
}
func manipulate(service Service) Service {
service.inc()
return service
}
func main() {
s := Service{}
s.inc()
s.inc()
fmt.Println("s", s)
t := manipulate(s)
fmt.Println("s", s) // still has counter 2!
fmt.Println("t", t) // is a copy and has counter 3!
}
For smaller data structures you can pass by value as well, but for larger this is not efficient, so pass by reference. DB conn for sure as reference. If this is about HTTP servers, this may be interresting: