嵌套依赖注入在golang中是否可以接受?

Are there any problems with nested dependency injection? For example:

type ParentService struct{
    db *sql.DB
}

type UsefulChildStruct struct{
    attrA int
    attrB int

    db *sql.Db

}

func NewParent(db *sql.DB) *ParentService{
    return &ParentService{db: db}
}

func (p *ParentService) NewChild() *UsefulChildStruct{
    return &UsefulChildStruct{db: p.db}
}

func (c *UsefulChildStruct) DoSomething(){
    x := c.db.SomeQuery
}

func (c *UsefulChildStruct) DoAnotherThing(){
    x := c.db.SomeQuery
}

func main(){
    db := getDB()
    parent := NewParent(db)
    child := parent.NewChild(parent.db)
}

The rationale is so all data types created by ParentService would be able to use the dependency too.

There is no problem in doing that.But you haven't created any value except complexity!

Another issue is you limited yourself, if you want to use differnet db for UsefulChildStruct later, you have to change your code. This is a violation of open for extension close for modification principle

i think you should do something like this but i'm not sure about syntax.

package main

type Storage interface {
    Get() (*Items, err)
}

type Items struct {
    foo string
}


// Postgres database
type postgres struct {
    db *sql.DB
}

func newPostgres(db *sql.DB) *postgres {
    return &postgres{db}
}

func (p *postgres) Get() (*items, error){
    // query something here
    return nil, nil
}



// Mongo database
type mongodb struct {
    mongo *session // i'am not sure about this 
}

func newMongo (session) *mongdb {
    return &mongdb{mongo: session}
}

func (m *mongdob) Get() (*items, error) {
    // query something here
    return nil, nil
}


// mock database
type mockDB struct {}

func newMock () mockDB {
    return mockDB{}
}

func (m mockDB) Get() (*items, error) {
    // query something here
    return nil, nil
}



type ParentService struct{
    db Storage
}

func NewParent(db Storage) *ParentService{
    return &ParentService{db: db}
}

func (p *ParentService) doSomething() {
    items, err := p.db.Get()
    // do something with items
}



func main(){
    db := connectPostgres()
    pStorage := newPostgres(db)
    parent := NewParent(pStorage)

    sess := connectMongo()
    mStorage := newMongo(sess)
    parent := NewParent(mStorage)

    mockStorage := mockDB()
    parent := NewParent(mockStorage)
}