Dependency injection - by value or by reference/pointer?

Hi,

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!
}

Output:

s { 2}
s { 2}
t { 3}

Always use pointers.

2 Likes

Hi Lutz,

I know the difference. But it is not about state changing objects - It is about a object graph which is created on booting the application.

But I don’t know if there is any convention for this.

My point is that ‘by value’ means that a copy is created. I don’t think this makes sense for a DB connection or a similar service.

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:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.