如何使结构接受两种类型之一作为参数?

I have a struct DbConnector which I want to use as a proxy to communicate with a database.

This struct has method Init(db *sql.DB).

Depending on conditions, I want to be able to initialise it with another struct, like DummyDatabaseConnection for testing.

How do I define the signature of Init() so that it accepts either *sql.DB or *DummyDatabaseConnection?

Define an Interface with some methods you need to call for *sql.DB & *DummyDatabaseConnection

type DBInterface interface {
    Ping() error
    Close() error
    // Some other Methods that you need
}

Now your DummyDatabaseConnection should satisfy your DBInterface.

type DummyDatabaseConnection struct {
}

func(d *DummyDatabaseConnection) Ping()error {
    return nil
}


func(d *DummyDatabaseConnection) Close()error {
    return nil
}

Use your Interface as argument

func (d *DbConnector) Init(db DBInterface) {
    db.Ping()
    db.Close()
}

Call with which one you need.

    dbConnector := &DbConnector{}

    // Call with *sql.DB
    db := &sql.DB{}
    dbConnector.Init(db)

    // Call with *DummyDatabaseConnection
    db := &DummyDatabaseConnection{}
    dbConnector.Init(db)

From your Init(db DBInterface) method, you only can call methods those are in DBInterface interface

Check this post

Hope this will help